본문 바로가기

개발하자

Python 기존 XLSM에 매크로 추가

반응형

Python 기존 XLSM에 매크로 추가

음. 매크로 xlsm 자료를 다 가지고 있어요. 워크북에 Workbook_Open vba 스크립트를 추가해야 합니다. 그러나 낮은 코드를 사용하면 모듈 섹션에 코드를 추가할 수 있습니다. 이 워크북' 섹션에 vba 코드를 추가해야 합니다.

location in vba

음. xlsm 데이터에 vbaProject.bin을 사용하는 것이 더 나을 수도 있습니다. 하지만 나는 이것이 xlswriter lib에서만 가능하다고 생각한다. 그리고 이 lib은 기존 xlsm에 vba를 추가할 수 없습니다 :(

누가 나를 도와줄 수 있나요?


# set file paths and macro name accordingly - here we assume that the files are located in the same folder as the Python script
pathToExcelFile = 'Dir/test.xlsx'
pathToMacro  = 'Dir/test/macro.txt'
myMacroName = 'UsefulMacro'

# read the textfile holding the excel macro into a string
with open (pathToMacro, "r") as myfile:
    print('reading macro into string from: ' + str(myfile))
    macro=myfile.read()

print(macro)


# open up an instance of Excel with the win32com driver
excel = win32com.client.Dispatch("Excel.Application")

# do the operation in background without actually opening Excel
excel.Visible = False

# open the excel workbook from the specified file
workbook = excel.Workbooks.Open(Filename=pathToExcelFile)

# insert the macro-string into the excel file
excelModule = workbook.VBProject.VBComponents.Add(1)
excelModule.CodeModule.AddFromString(macro)

# run the macro
#excel.Application.Run(myMacroName)
xlOpenXMLWorkbookMacroEnabled = 52

# save the workbook and close
#excel.Workbooks(1).Close(SaveChanges=1)
excel.Workbooks(1).SaveAs('testneu.xlsm', FileFormat=xlOpenXMLWorkbookMacroEnabled)
#wb.SaveAs(filename, FileFormat=xlOpenXMLWorkbookMacroEnabled)
excel.Application.Quit()

# garbage collection
del excel



다음 코드를 사용해 보십시오:

import win32com.client

xl = win32com.client.Dispatch("Excel.Application")

code = 'Private Sub Workbook_Open() \n \
            MsgBox "Hello!" \n \
        End Sub'

path = r'c:\Users\Alex20\Documents\test.xlsm'
wb = xl.Workbooks.Open(path)
wb.VBProject.VBComponents(1).CodeModule.AddFromString(code)
#xl.Visible = True
wb.Close(True)
xl.Quit()

이전:

Before

이후:

After

실행 중:

Running


반응형