Running VBA code from Python: macros may be disabled - python

Trying to run an Excel macro via Python I get the following error:
Traceback (most recent call last):
File ".\test.py", line 17, in <module>
xlApp.Application.Run(MACRO)
File "<COMObject <unknown>>", line 14, in Run
File "C:\Users\twauchop\Desktop\Python\virtual_envs\gutenberg\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Cannot run the macro 'test'. The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None)
I tried many of the fixes suggested in other questions.
I tried 'xlApp.Application.Run(wb.name + "!" + MACRO)'.
Is this a naming convention issue? I enabled everything via Trust Center and changed the VBA sub to public.
As a side-note, I also cannot run macros from the programmatically opened workbook (i.e. if I try manually). If I open the workbook manually, however, everything is fine.
I am running Python 3.6.5 on a 64 bit system, Windows 10.
Python:
import win32com.client
import os
import traceback
DIRECTORY = r'C:\\Users\\twauchop\\Desktop\\Excel\\'
FILE = 'test.xlsb'
MACRO = 'test'
path = os.path.join(DIRECTORY, FILE)
if os.path.exists(path):
try:
xlApp = win32com.client.Dispatch('Excel.Application')
xlApp.DisplayAlerts = False
xlApp.Visible = True
wb = xlApp.Workbooks.Open(Filename=path, ReadOnly=1)
xlApp.Application.Run(MACRO)
wb.Close(SaveChanges=1)
xlApp.Application.Quit()
print('Code ran successfully.')
except:
print('An error was encountered; see traceback.')
print(traceback.format_exc())
xlApp.Quit()
VBA:
Public Sub test()
MsgBox "Hello World!"
End Sub

xlApp.Application.AutomationSecurity=1 needs to go before ANY xlApp.Application.Run(excelMacroNameHere) code, as the AutomationSecurity is used to control (enable vs disable) macros and 1 means enable all macros.

Related

Use PyWin32 to execute VBA Macro from Python

I have two Excel Files and I can execute Macro ReadBM_AP_Data, but not PythonScript. For this function I used PyWin32 with the Function RunApplication
Here is the Python Code:
xl = win32com.client.Dispatch("Excel.Application", pythoncom.CoInitialize())
#C:\Users\dx5entir\PycharmProjects\pythonProject
xl.Workbooks.Open("C:/Users/dx5entir/PycharmProjects/pythonProject/FapsXML.xlsm")
xl.RunApplication("FapsXML.xlsm!Modul1.PythonScript()")
#xl.Application.Run('ReadEC_DC_Data.xlsm!Modul2.ReadBM_AP_Data()')
xl.Application.Quit()
If I open the Excel File and start PythonScript it works.
This is the Error Messages:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\dx5entir\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\observers\api.py", line 205, in run
self.dispatch_events(self.event_queue)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\observers\api.py", line 381, in dispatch_events
handler.dispatch(event)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\watchdog\events.py", line 271, in dispatch
self.on_any_event(event)
File "C:\Users\dx5entir\PycharmProjects\pythonProject\main.py", line 54, in on_any_event
start_xl()
File "C:\Users\dx5entir\PycharmProjects\pythonProject\main.py", line 68, in start_xl
xl.Application.Run("FapsXML.xlsm!Modul1.PythonScript()")
File "<COMObject >", line 8, in Run
File "C:\Users\dx5entir\PycharmProjects\pythonProject\venv\Lib\site-packages\win32com\client\dynamic.py", line 368, in ApplyTypes
result = self.oleobj.InvokeTypes(
^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_Serror: (-2147352567, 'Ausnahmefehler aufgetreten.', (0, 'Microsoft Excel', "Das Makro 'FapsXML.xlsm!Modul1.PythonScript()' kann nicht ausgeführt werden. Das Makro ist möglicherweise in dieser Arbeitsmappe nicht verfügbar, oder alle Makros wurden deaktiviert.", 'xlmain11.chm', 0, -2146827284), None)
I implement a watchdog to trigger this Event, but it still works with the other macro, so I see no problem with that.
Name Excel Sheets:
Name of Module and Sub:
At the beginning my Excel Sheets had spaces. So I fixed that.
I tried other macros and they worked. This macro PythonScript is working when I start it manually in the Excel file.
I called the function per Button and not trigger it with a watchdog event. Same error.
I updated my PythonInterpreter to Python 3.11.1 and updated every Python Packages in my Enviroment
Im confused why this function doesn't work with this macro, when this macro works when i start it manually and other macros works when I use PyWin32. I have no clue to fix that problem. Any advices? :)

Running an Excel macro via Python? (New problem - saving)

I already saw this question in other link but I'm new here and i don't have reputation to comment there.
I made the script works and the macro run but when saving the file instead of just saving, it opens a excel pop-up asking if i confirm the changes. How do I save directly without opening this pop-up?
my code (edited):
import os.path
import win32com.client as wincl
if os.path.exists("C:\\Users\\peo_cpena\\Downloads\\excel.xlsx"):
try:
xl = wincl.Dispatch("Excel.Application")
xl.Workbooks.Open(os.path.abspath(
"C:\\Users\\peo_cpena\\Downloads\\excel.xlsx"))
xl.Application.Run("macro2.xlsm!Macro2")
xl.Application.Workbooks("excel.xlsx").Save()
xl.Application.DisplayAlerts = False
xl.Application.Workbooks("excel.xlsx").Quit(False)
del xl
except:
xl.Application.Quit()
print("It didn't work")
del xl
Removing the Try i received this error:
Traceback (most recent call last):
File "C:/Users/peo_cpena/PycharmProjects/Cursoemvideo/UOL/CalculoImpARG.py", line 14, in <module>
xl.Application.Workbooks("C:\\Users\\peo_cpena\\Downloads\\Vendas_por_Repasse_Aeria_Games_Europe_GmbH_01102020-31102020.xlsx").Save()
File "C:\Users\peo_cpena\PycharmProjects\Cursoemvideo\venv\lib\site-packages\win32com\client\dynamic.py", line 197, in __call__
return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352567, 'Exceção.', (0, None, None, None, 0, -2147352565), None)
Try explicitly saving the workbook before closing it:
xl.Application.Workbooks("excel.xlsx").Save()
xl.Application.Workbooks("excel.xlsx").Close(False)

Unable to save file on XLWings

[USING XLWINGS PACKAGE]
I'm attempting to open an excel spreadsheet (existing), write data to specified cells, and then use the workbook.save() function to save the file to a new file name (as not to overwrite)
Right now I currently have:
app = xw.App(visible = False)
wbMain = wx.Book('Example.xlsm') #Open premade excel file
sheetMain = wbMain.sheets['Example']
sheetMain.range('A1').value = 'Test' #Modify value of cell A1
wbMain.save('NewFileName.xlsm') #Save to new filename
wbMain.close() #Close current excel sheet
app.kill() #Kill program (may not work)
(Sorry about my formatting if it's off)
Here is my traceback:
Traceback (most recent call last):
File "C:\Users\USER\Desktop\test_proj\main.py", line 34, in <module>
wbMain.save(NewFileName.xlsm)
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\main.py", line 688, in save
return self.impl.save(path)
---
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 472, in save
self.xl.SaveAs(os.path.realpath(path))
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 63, in __call__
v = self.__method(*args, **kwargs)
---
File "<COMObject Open>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft
Excel', 'SaveAs method of Workbook class failed', 'xlmain11.chm', 0,
-2146827284), None)
I've tried lookin at the XLWings documentation and various other stackoverflow threads but none seemed to offer a solution that worked. Has anyone had the same issue before?
I had the same problem - turns out using the full path in wbMain.save('C:/xxx/NewFileName.xlsm') worked for me.
Credits to #aneroid for the help! See here: xlwings: Save and Close

Opening Word from Python, unexpected behaviour

I'm writing a script to parse word document and get certain outputs. I use the following commands for reading the desired document.
import win32com.client as win32
import Tkinter,tkFileDialog
root = Tkinter.Tk()
root.withdraw()
filename = tkFileDialog.askopenfilename() # getting filename through windows explorer
word = win32.Dispatch("Word.Application")
#word.Documents.Open(filename)
The last line which is commented is how I was planning to implement this. But whenever I try to open a file which has a space in it's filename, this fails. In fact I found that if I give word.Documents.Open("C:/Python27/word sample.docm")
This will also fail, but if I use backslash after C: it'll work perfectly.
In short the below commands for opening document will work:
word.Documents.Open("C:\Python27/word sample.docm")
word.Documents.Open(filename) #if filename don't have a space
And the below ones will not work:
word.Documents.Open("C:/Python27/word sample.docm")
word.Documents.Open(filename) #filename have a space in it
Could someone explain what is going wrong here?
This is the error that I'm receiving:
C:\Users\xxx>C:\Python27\python.exe C:\Python27\test.py
Traceback (most recent call last):
File "C:\Python27\test.py", line 10, in <module>
word.Documents.Open("C:/Python27/word sample.docm")
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Word'
, u'This file could not be found.\r (C:\\//Python27/word%20sample.docm)', u'
wdmain11.chm', 24654, -2146823114), None)

How to catch a pywin32com exception on opening files

I am trying to open an excel file in python using COM, and trying to catch the file not found error:
I first tried catching the IOError:
try:
output = xl.Workbooks.Open(Params.workbookName)
except IOError as reason:
print reason
exit()
But COM doesn't raise an IO Error when it has a file not found problem, instead it raises something called com_error:
com_error: (-2147352567, 'Exception
occurred.', (0, u'Microsoft Office
Excel', u"'asdf.xlsx' could not be
found. Check the spelling of the file
name, and verify that the file
location is correct.\n\nIf you are
trying to open the file from your list
of most recently used files, make sure
that the file has not been renamed,
moved, or deleted.", u'C:\Program
Files (x86)\Microsoft
Office\Office12\1033\XLMAIN11.CHM',
0, -2146827284), None)
so logically I tried this:
try:
output = xl.Workbooks.Open(Params.workbookName)
except com_error as reason:
print reason
exit()
but...
NameError: global name 'ComError' is not defined
Try:
from pythoncom import com_error
and catch it in your except block

Categories