1

I'm using the following code to add a Macro to Excel. I notice that the data / other WorkSheets from the original Excel had dropped completely but the Macro is showing.

This is the code that I am using:

import xlsxwriter
workbooks = xlsxwriter.Workbook('C:\\Users\\user\Desktop\\test.xlsm')
workbooks.add_vba_project('C:\\Users\\user\\Desktop\\vbaProject.bin')
workbooks.close()

I used the link http://xlsxwriter.readthedocs.io/example_macros.html and it seems to be the same from another page https://redoakstrategic.com/pythonexcelmacro/

I wondered if there is another library that I should use for this?

I tried the following link Use Python to Inject Macros into Spreadsheets it seems that here again the data from the original file is overwritten. Not sure if this is a duplicate or not, or if I missed something rather obvious ?

Thanks

Community
  • 1
  • 1
Sam Jinko
  • 13
  • 6

2 Answers2

1

Unfortunately, xlsxwriter can't load information from already existing Excel workbooks; it is only used for making new ones. You are overwriting your old workbook with a blank one that has your macros.

If you need to load information, look into openpyxl. It can be used for creating .xlsm files.

Charlie B.
  • 36
  • 9
0

One way around it is to create the macro you want in another Excel so we can execute it to affect the other Excel. Then using win32.com it runs the VBA.

enter code here
#import win32com.client
#xl=win32com.client.Dispatch("Excel.Application")
#xl.Workbooks.Open(Filename="C:\\macro.xlsm",ReadOnly=1)
#xl.Application.Run("macro")
#xl = 0
Sam Jinko
  • 13
  • 6