I am trying to pass the variable Nothing
in VBA using Python's win32com
. I tried to use None
but it returned 'Type dismatch.'
Could anyone please help?
Thank you!
An example:
' Book1.xlsm!Module1
Function test(arg As Object) As String
If arg Is Nothing Then
test = "Success"
Exit Function
Else
test = "Failure"
Exit Function
End If
End Function
And in Python:
import win32com.client
import os
import pythoncom
xl = win32com.client.Dispatch('Excel.Application')
xl.Visible = True
xl.Workbooks.Open(Filename=os.path.abspath('Book1.xlsm'))
test_str = xl.Application.Run('Book1.xlsm!Module1.test', pythoncom.Empty)
The REPL says:
runfile('C:/Users/shwang/Downloads/untitled0.py', wdir='C:/Users/shwang/Downloads')
Traceback (most recent call last):
File "<ipython-input-22-301693920f2c>", line 1, in <module>
runfile('C:/Users/shwang/Downloads/untitled0.py', wdir='C:/Users/shwang/Downloads')
File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/shwang/Downloads/untitled0.py", line 16, in <module>
test_str = xl.Application.Run('Book1.xlsm!Module1.test', pythoncom.Empty)
File "<COMObject <unknown>>", line 14, in Run
File "C:\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352561), None)
In VBA,
Nothing
is used as the uninitialized default valueObject
type which usually references COM objects (i.e., Excel object library or external application's object library). VBA's primitive integer, long, and string types cannot be assigned the Nothing value. And usually programmers use this at the end of code block to release objects from memory.Hence, there is no strict translation between VBA's
Nothing
(a special value for COM types) and Python's value types includingNone
which crudely means empty or no value for any type.With that said, your code will not err out if you pass a COM object which you already initialize with
xl
. Below outputsFAILURE
. If somehow you can declare an uninitialized COM object which then will carry Nothing then you can pass that into your function. But to callDispatch
requires a named object. Catch-22!