I want to execute a macro/function code with python script. I have this code example:
from win32com.client import Dispatch
objAccess = Dispatch("Access.Application")
objAccess.Visible = False
objAccess.OpenCurrentDatabase(strDbName)
objDB = objAccess.CurrentDb()
objAccess.DoCmd.RunMacro('MyMacro')
objAccess.Application.CloseCurrentDatabase()
objAccess.Application.Quit()
del objAccess
del objDB
But I get this error:
Traceback (most recent call last):
File "D:\workspace-python\TOOLS\SHPTOOL\test.py", line 8, in <module>
objAccess.DoCmd.RunMacro('MyMacro')
File "<COMObject <unknown>>", line 3, in RunMacro
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, u"Microsoft Office Access can't find the object 'MyMacro.'", u'ACMAIN11.CHM', 10183, -2146825803), None)
Then I try another approach, call RUN method:
objAccess = Dispatch("Access.Application")
objAccess.Visible = False
objAccess.OpenCurrentDatabase(strDbName)
objDB = objAccess.CurrentDb()
objAccess.Run('merge', "mystringparameter")
objAccess.Application.Quit()
error:
Traceback (most recent call last):
File "D:\workspace-python\TOOLS\SHPTOOL\test.py", line 58, in <module> objAccess.Run('merge', "mystringparameter")
File "<COMObject Access.Application>", line 14, in Run
File "C:\Python27\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, None, u"Microsoft Office Access can't find the procedure 'merge.'", None, -1, -2146825771), None)
And my MDB code, the 3 functions:
Sub merge(path As String)
MsgBox "Inside generated macro!!! " & path
End Sub
Sub MyMacro()
MsgBox "Inside generated macro!!!"
End Sub
Function MyFunction()
MsgBox "You MUST select a Destination Folder!"
End Function
Thanks
Just replace
objAccess.DoCmd.RunMacro('MyMacro')
by
objAccess.run('MyMacro')
\o/
Related
I have an issue by acquiring a VirtualBox Virtual Machine, here's the error code I am getting with the code bellow :
Traceback (most recent call last):
File "C:\Users\ROULLE Diego\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualbox\library_base.py", line 209, in _call_method
ret = method(*in_params)
File "C:\Users\ROULLE~1\AppData\Local\Temp\gen_py\3.10\D7569351-1750-46F0-936E-BD127D5BC264x0x1x3.py", line 12824, in CreateMachine
ret = self._oleobj_.InvokeTypes(1610743849, LCID, 1, (9, 0), ((8, 1), (8, 1), (8200, 1), (8, 1), (8, 1), (8, 1), (8, 1), (8, 1)),aSettingsFile
pywintypes.com_error: (-2147352561, 'Paramètre non facultatif.', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\ROULLE Diego\Desktop\run_vms.py", line 22, in <module>
pool_web1.acquire("jouca", "troll"),
File "C:\Users\ROULLE Diego\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualbox\pool.py", line 158, in acquire
clone = machine.clone(name="%s Pool" % self.machine_name)
File "C:\Users\ROULLE Diego\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualbox\library_ext\machine.py", line 139, in clone
vm_clone = vbox.create_machine(settings_file, name, groups, "", create_flags)
File "C:\Users\ROULLE Diego\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualbox\library.py", line 10462, in create_machine
machine = self._call(
File "C:\Users\ROULLE Diego\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualbox\library_base.py", line 200, in _call
return self._call_method(method, in_p=in_p)
File "C:\Users\ROULLE Diego\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualbox\library_base.py", line 222, in _call_method
errobj.msg = exc.args[2][2]
TypeError: 'NoneType' object is not subscriptable
The code :
from virtualbox import VirtualBox, pool
vbox = VirtualBox()
pool_web1 = pool.MachinePool("Web1")
pool_web2 = pool.MachinePool("Web2")
pool_sql1 = pool.MachinePool("SQL1")
sessions = []
while True:
print("1 : create run")
print("2 : release last run")
print("3 : clear all runs")
print("4 : show all ips")
print()
command = input("Command : ")
match command:
case "1":
sessions.append([
pool_web1.acquire("jouca", "troll"),
pool_web2.acquire("jouca", "troll"),
pool_sql1.acquire("jouca", "troll")
])
break
I tried to acquire the VM machine by the MachinePool and it resulted to an error.
xlwings works fine on my computer, but when I try to transfer the same set up to another computer it seems to not open correctly giving me this error
Traceback (most recent call last):
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 432, in __call__
return Book(xl=self.xl(name_or_index))
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 152, in __call__
v = self._inner(*args, **kwargs)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\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, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 2776, in open
impl = self.impl(name)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 434, in __call__
raise KeyError(name_or_index)
KeyError: 'output2019-06-03.11-40timeseries_5-31-2019scrubbed.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Computation.py", line 157, in <module>
xwWb = xw.Book("output" + timeName + os.path.split(file_path)[1])
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 488, in __init__
impl = app.books.open(fullname).impl
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 2787, in open
impl = self.impl.open(fullname)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 443, in open
return Book(xl=self.xl.Open(fullname))
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 63, in __call__
v = self.__method(*args, **kwargs)
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)
Here is some simplified code where none of the data changing is occurring. Using ospath absolute does not help with the error. Both systems run the same 64 bit operating system and 32 bit excel. Yet the error persists on the second machine. There is no real difference I can understand that would give me an error on the 2nd system over the first one. Both machines are PCs
import xlrd
import openpyxl
import xlwings as xw
from xlwings import constants
import os
import tkinter as tk
from tkinter import filedialog
import datetime
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
start = time.time()
wb = openpyxl.load_workbook(file_path)
Returns = wb['Prices']
newWs = wb.create_sheet()
newWs.title = "NominalDailyReturns"
benchWS = wb.create_sheet()
benchWS.title = "ActiveDailyReturns"
thirdWs = wb.create_sheet()
thirdWs.title = "RawAnalysis"
thirdWs.column_dimensions["A"].width = 32
name4 = thirdWs.title
print("halfway")
print(os.path.split(file_path))
print("output" + timeName + os.path.split(file_path)[1])
wb.save("output" + timeName + os.path.split(file_path)[1])
xwWb = xw.Book(os.path.abspath("output" + timeName + os.path.split(file_path)[1]))
XnewWs = xwWb.sheets['NominalDailyReturns']
xwWb.save()
xwWb.close()
wb = openpyxl.load_workbook("output" + timeName + os.path.split(file_path)[1])
benchWS = wb['ActiveDailyReturns']
wb.save("output" + timeName + os.path.split(file_path)[1])
xwWb = xw.Book("output" + timeName + os.path.split(file_path)[1])
XthirdWs = xwWb.sheets['RawAnalysis']
xwWb.save()
xwWb.close()
I figured out the problem with my code. When I used openpyxl to edit my excel data, one of the formulas was subtracting a word from a number, raising an error and corrupting the excel file. Then xlwings tried to open a corrupted file, and it failed on me.
So the solution is to not save a corrupted excel file and expect xlwings to open it.
I am trying to use evdev to simulate touch input.
from evdev import UInput, AbsInfo, ecodes as e
cap = {
e.EV_KEY : [e.KEY_A, e.KEY_B],
e.EV_ABS : [
(e.ABS_X, AbsInfo(value=0, min=0, max=255,
fuzz=0, flat=0, resolution=0)),
(e.ABS_Y, AbsInfo(0, 0, 255, 0, 0, 0)),
(e.ABS_MT_POSITION_X, (0, 255, 128, 0)) ]
}
ui = UInput(cap, name='example-device', version=0x3)
Adding myself to the input group, the error is:
Traceback (most recent call last):
File "mouse.py", line 12, in <module>
ui = UInput(cap, name='example-device', version=0x3)
File "/home/user/.virtualenvs/venv/lib/python3.6/site-packages/evdev/uinput.py", line 125, in __init__
self._verify()
File "/home/user/.virtualenvs/venv/lib/python3.6/site-packages/evdev/uinput.py", line 221, in _verify
raise UInputError(msg.format(self.devnode))
evdev.uinput.UInputError: "/dev/uinput" cannot be opened for writing
After running chmod +0666 /dev/uinput the error changes to:
Traceback (most recent call last):
File "mouse.py", line 12, in <module>
ui = UInput(cap, name='example-device', version=0x3)
File "/home/user/.virtualenvs/venv/lib/python3.6/site-packages/evdev/uinput.py", line 147, in __init__
_uinput.create(self.fd, name, vendor, product, version, bustype, absinfo)
SystemError: /builddir/build/BUILD/Python-3.6.2/Objects/longobject.c:404: bad argument to internal function
Removing (e.ABS_MT_POSITION_X, (0, 255, 128, 0)):
Traceback (most recent call last):
File "mouse.py", line 12, in <module>
print(ui)
File "/home/user/.virtualenvs/venv/lib/python3.6/site-packages/evdev/uinput.py", line 171, in __str__
evtypes = [i[0] for i in self.capabilities(True).keys()]
File "/home/user/.virtualenvs/venv/lib/python3.6/site-packages/evdev/uinput.py", line 200, in capabilities
raise UInputError('input device not opened - cannot read capabilites')
evdev.uinput.UInputError: input device not opened - cannot read capabilites
I am trying to get a named Range in code like this:
Range(rng_name, index=False).value = df_grouped_a.ix[loc][col]
This generates exception:
File "C:/Users/acme/python/s.py", line 149, in <module>
Range(rng_name, index=False).value = df_grouped_a.ix[loc][col]
File "C:\Program Files (x86)\Python271\lib\site-packages\xlwings\main.py", line 620, in __init__
self.row1 = xlplatform.get_first_row(self.xl_sheet, range_address)
File "C:\Program Files (x86)\Python271\lib\site-packages\xlwings\_xlwindows.py", line 122, in get_first_row
return xl_sheet.Range(range_address).Row
File "<COMObject <unknown>>", line 3, in Range
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None)
It might be related to the named range issue, but I would like to get the meaning of error code -2146827284 first.
Unfortunately, the way described here does not work for me: https://stackoverflow.com/a/36080159
Namely:
>>> import win32api
>>> win32api.FormatMessage(-2146827284)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pywintypes.error: (15100, 'FormatMessage', 'The resource loader failed to find MUI file.')
How can I find the error message corresponding to this error code?
-2146827284 may be represented as 0x80020009, is a COM Error Code. That mean DISP_E_EXCEPTION - Basic value returned if COM exception ooccured.
Simpliest way to 'convert' singed int to unsigned is to apply bitwise & 0xFFFFFFFF operation.
>>> error = -2146827284
>>> error & 0xffffffff
2147614729
But nothing special you will see when try to
>>> win32api.FormatMessage(error)
Exception occurred.
I'm trying to add an Excel Document within another Excel Document using OLEObjects in Python, but I'm getting this error:
d:\Python\PythonReport>d:/Python27/python.exe genDP.py d:/Python/PythonReport/ATP.xlsx
Traceback (most recent call last):
File "genDP.py", line 219, in <module>
add_ATP_WorkBook(OutputBook, sys.argv[1])
File "genDP.py", line 212, in add_ATP_WorkBook
oleObjects.Add(ClassType=None, Filename=file, Link=False, DisplayAsIcon=False, Left=0, Top=0, Width=50, Height=50)
File "<COMObject OLEObjects>", line 6, in Add
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u'Add method of OLEObjects class failed', u'C:\\Program Files (x86)\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None)
What is strange is the fact that it works well for other files: I could easily add a text document as OLEObject, but when I try with an Excel Document I get that error.
This is the code:
def add_ATP_WorkBook(OutputBook, file):
ExcelApp = win32com.client.Dispatch("Excel.Application")
ExcelApp.visible = 1
workbook = ExcelApp.Workbooks.open(str(os.path.abspath(os.path.dirname(sys.argv[0])))+"\DVPR Report.xls")
oleObjects = workbook.ActiveSheet.OLEObjects()
oleObjects.Add(ClassType=None, Filename=file, Link=False, DisplayAsIcon=False, Left=0, Top=0, Width=50, Height=50)
workbook.Worksheets('Recognition Rate').Activate()