当使用 ExecuteExcel4Macro 在 Python 中运行 Excel 宏时,我总是得到 False 结果,这是执行的代码:
import win32com.client
filename = r'E:\excel.xls'
xlApp = win32com.client.Dispatch('Excel.Application')
xlApp.visible = 1
xlBook = xlApp.Workbooks.Open(filename)
strPara = xlBook.Name + '!Macro1()'
res = xlApp.ExecuteExcel4Macro(strPara)
print res
xlBook.Close(SaveChanges=0)
“print res”语句的输出是:False
我在MSDN 上搜索了ExecuteExcel4Macro 的用法之后| ,我得到以下信息:
ExecuteExcel4Macro -- Runs a Microsoft Excel 4.0 macro function and then returns the result of the function. The return type depends on the function.
然后我就糊涂了:既然Excel中的宏总是一个“子过程”,而VBA中的“子过程”是没有返回结果的,那么Excel宏怎么可能返回结果呢?那么上面例子中的False结果代表什么呢?
之后,我尝试在 Excel(2003) 中使用 ExecuteExcel4Macro,而不是使用 Python 而是使用 VBA 进行编码:
Sub RunMacro()
res = ExecuteExcel4Macro("excel.xls!Macro1()")
MsgBox CStr(res)
End Sub
Sub Macro1()
MsgBox "in Macro1"
End Sub
与MsgBox中显示的“res”字符串相同:False
1.为什么ExecuteExcel4Macro的返回结果总是False?
2.在Python中运行Excel宏并获取Excel宏函数的退出状态怎么办?
更新于 2011.10.28:
Sub TEST()
res = Application.Run(MacroToRun)
MsgBox CStr(res)
End Sub
Function MacroToRun()
MacroToRun = True
End Function
在 Excel 2003 中运行 TEST Macro 后,我得到:
包含“错误 2015”信息的对话框。
请您参考如下方法:
您可以定义 Excel 函数,不是以 sub 开头,而是以 function 开头:
Function Area(Length As Double, Optional Width As Variant)
If IsMissing(Width) Then
Area = Length * Length
Else
Area = Length * Width
End If
End Function
这应该返回一些东西。 This something 是以函数命名的变量的内容(这里是 Area)。
