如何使用 Python win32com 调用 Excel VBA 函数和子函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14732340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 19:30:00  来源:igfitidea点击:

How to call Excel VBA functions and subs using Python win32com?

pythonexcelvbawin32com

提问by Yulia V

My Excel workbook contains VBA subs and macros similar to those below; they sit in Module1.

我的 Excel 工作簿包含与以下类似的 VBA 子程序和宏;他们坐在模块 1 中。

How to call them using Python win32com module?

如何使用 Python win32com 模块调用它们?

Public Sub setA1(ByVal s As String)
    ThisWorkbook.ActiveSheet.Range("A1").Value = s
End Sub

Public Function getA1() As String
    getA1 = ThisWorkbook.ActiveSheet.Range("A1").Value
End Function

Many thanks in advance!

提前谢谢了!

回答by Yulia V

import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="c:\temp\book1.xls",ReadOnly=1)
xl.Application.Run("setA1", '4')
res = xl.Application.Run("getA1")
print res
xl = 0

Just as simple as this ....

就这么简单......