2013-07-01 4 views
2

TIBCO Spotfire v4를 실행 중입니다. IronPython이 내장되어 있습니다. .xls 파일을 내보낼 Spotfire 보고서를 실행하려고합니다 (해당 부분이 완료되었습니다). Excel 파일을 열고 파일을 포맷 할 수있는 매크로를 실행하는 스크립트를 찾고 있습니다.IronPython - Excel 매크로 실행

다음은 사용하고 발견 한 코드입니다. 가져 오기 항목의 출처가 확실하지 않습니다.

import os, os.path, win32com.client 

def run_macro(fName, macName, path=os.getcwd()): 
    """ 
    pre: fName is the name a valid Excel file with macro macName 
    post: fName!macName is run, fName saved and closed 
    """ 
    fName = os.path.join(path, fName) 
    xlApp = win32com.client.Dispatch("Excel.Application") 
    fTest = xlApp.Workbooks.Open(fName) 
    macName = fTest.Name + '!' + macName xlApp.Run(macName) 
    fTest.Close(1) 
    xlApp.Quit() 
    xlApp = None 

편집기 - 코드 Cannot iterate VBA macros from Python에서 보낸 것으로 보인다.

+0

보여줄 수 : 내가 솔루션을 찾고 때

# recognizing an already opened window from System.Runtime.InteropServices import Marshal excel = Marshal.GetActiveObject("Excel.Application") 

이 링크는 매우 유용했다? –

+0

다음은 사용하고 찾은 코드입니다. 가져 오기 항목의 출처가 확실하지 않습니다. pre : fName은 매크로가있는 유효한 Excel 파일 이름입니다. post : fName! macName is running, fName = 저장 한 후 닫음 "" "fName = os.path.join (경로, fName) xlApp = win32com.client.Dispatch ("Excel.Application ") fTest = xlApp.Workbooks.Open (fName) macName = fTest.Name + ! ' + macName xlApp.Run (macName) fTest.Close (1) xlApp.Quit() xlApp = None – user2540187

+0

기존 답변에서 질문을 다루는 것처럼 보였습니다. 시도해 보았습니까? 그렇다면 허용 된 답변으로 표시하거나 여전히 올바르지 않은 것을 알려주는 것이 좋습니다. – RyanfaeScotland

답변

2

나는 비슷한 문제 (ipy에서 Excel VBA 매크로를 실행하려고 시도 함)를 가졌으며 작동이 끝났습니다. 첫번째 섹션은 .NET을 사용하고, 두 번째 부분은 실제로 매크로 실행

# .net access 
import clr 
clr.AddReference("Microsoft.Office.Interop.Excel") 

# opening the workbook 
excel = Excel.ApplicationClass() 
excel.Visible = True 
excel.DisplayAlerts = False 
workbook = excel.Workbooks.Open(r"C:\your\file\here.xls") 
# or open locally: 
# workbook = ex.Workbooks.Open('here.xls') 

# running the macro 
excel.Run('YOUR-MACRO-NAME') 

# closing down 
excel.Exit() 

:

이 코드를보십시오. 이것은 열려 있지 않은 Excel 파일에서 Excel 코드를 실행하는 것입니다. 이미 열려있는 파일에서 매크로를 실행하고 싶다면 (내가해야만하는 것, 여기에 넣을 수도 있습니다), 매크로를 열지 않고 활성 객체로 인식해야합니다. 이하). 매크로를 실행하는 코드는 여전히 위와 같습니다. 당신이 무엇을 시도했다 당신은 우리를

http://www.ironpython.info/index.php?title=Interacting_with_Excel

+1

DisplayAlerts 행을 예외 (알려진 버그가있는 것 같습니다)로 던져서 excel.Exit() 대신 excel.Quit()를 사용했지만 올바른 답이 +1 인 것 이외에는 DisplayAlerts 행을 주석 처리해야했습니다. – RyanfaeScotland