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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.