반응형
Python 기존 XLSM에 매크로 추가
음. 매크로 xlsm 자료를 다 가지고 있어요. 워크북에 Workbook_Open vba 스크립트를 추가해야 합니다. 그러나 낮은 코드를 사용하면 모듈 섹션에 코드를 추가할 수 있습니다. 이 워크북' 섹션에 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()
이전:
이후:
실행 중:
반응형
'개발하자' 카테고리의 다른 글
| node in typescript(노드 v17.6)에서 native fetch를 사용하려면 어떻게 해야 합니까 (1) | 2023.10.17 |
|---|---|
| kubernetes에서 DNS를 확인할 수 없습니다 (0) | 2023.10.16 |
| Kubernetes로 배포하고 Ingress를 통해 연결한 후 SSE가 끊어짐 (2) | 2023.10.15 |
| helm의 '--dry-run' 옵션은 kubernetes API 서버에 연결이 필요한가? 면방향 연결 오류 (0) | 2023.10.15 |
| 창에서 주피터 노트북에서 사용하는 기본 브라우저를 변경하는 방법 (0) | 2023.10.14 |



