컴퓨터/Python

python vba매크로 포함 파일 만들기

풍경소리^^ 2022. 10. 10. 11:07

한계 : xlsxwriter 사용함으로써

           기존 엑셀파일을 읽어서 워크시트를 추가 또는 수정이 불가능하다.

 

1 단계 vba_extract.py 위치를 찾는다

           저의 경우 C:\Users\DESKTOP-millni\AppData\Local\Programs\Python\Python310\Scripts\vba_extract.py

2단계 기존 매크로가 있는 원본엑셀파일

          E:\python\vscode\pay\excel_data\급여대장m.xlsm

3단계 윈도우 폴더 창을 띄워놓고 주소창에 내가 실행할 파이썬 파일이 있는 위치에서

          E:\python\vscode\pay 

          cmd 엔터 

4단계 다음을 한 문장으로 입력 후 엔터

          C:\Users\DESKTOP-millni\AppData\Local\Programs\Python\Python310\Scripts\vba_extract.py

             E:\python\vscode\pay\excel_data\급여대장m.xlsm

결과 Extracted: vbaProject.bin

         vba매크로 바이너리 파일 생성 완료

 

macro.py--------------------

import xlsxwriter

# Note the file extension should be .xlsm.
workbook = xlsxwriter.Workbook(r'E:\python\vscode\pay\excel_data\macro1.xlsm') # vba매크로 넣어 생성할 파일명
worksheet = workbook.add_worksheet()

worksheet.set_column('A:A', 30)

# Add the VBA project binary.
workbook.add_vba_project('./vbaProject.bin')

# Show text for the end user.
worksheet.write('A3', 'Press the button to say hello.')

# Add a button tied to a macro in the VBA project.
worksheet.insert_button('B3', {'macro': 'say_hello',
                               'caption': 'Press Me',
                               'width': 80,
                               'height': 30})

workbook.close()

 

마지막

python macro.py 실행

https://xlsxwriter.readthedocs.io/working_with_macros.html

 

Working with VBA Macros — XlsxWriter Documentation

This section explains how to add a VBA file containing functions or macros to an XlsxWriter file. The Excel XLSM file format An Excel xlsm file is exactly the same as an xlsx file except that is contains an additional vbaProject.bin file which contains fun

xlsxwriter.readthedocs.io