gpt4 book ai didi

python - 为什么ExecuteExcel4Macro的返回结果总是False?

转载 作者:太空宇宙 更新时间:2023-11-04 06:38:10 25 4
gpt4 key购买 nike

当使用 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)。

关于python - 为什么ExecuteExcel4Macro的返回结果总是False?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7782524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com