我在看如何使用 xlwings 从 Python 调用 Excel 宏?,我知道它没有得到完全支持,但我想知道是否有办法做到这一点。
有些像:
from xlwings import Workbook, Application
wb = Workbook(...)
Application(wb).xl_app.Run("your_macro("%Args%")")
Run Code Online (Sandbox Code Playgroud)
这可以通过执行您的建议来完成。但是请记住,此解决方案不会跨平台 (Win/Mac)。我在 Windows 上,所以下面必须调整为 Mac 上的 appscript。http://docs.xlwings.org/en/stable/missing_features.html
可以通过以下方式调用 VBA 脚本:
linked_wb.xl_workbook.Application.Run("vba_script", variable_to_pass)
Run Code Online (Sandbox Code Playgroud)
示例:假设您有一个字符串列表,应该在 Excel 的数据验证列表中使用
Python:
from xlwings import Workbook
linked_wb = Workbook.caller()
animals = ['cat', 'dog', 'snake', 'bird']
animal_list = ""
for animal in animals:
animal_list += animal + "|"
linked_wb.xl_workbook.Application.Run("create_validation", animal_list)
Run Code Online (Sandbox Code Playgroud)
Excel VBA:
Public Sub create_validation(validation_list)
Dim validation_split() As String
validation_split = Split(validation_list, "|")
'The drop-down validation can only be created with 1-dimension array.
'We get 1-D from the Split above
With Sheet1.Range("A1").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:=Join(validation_split, ",")
End With
End Sub
Run Code Online (Sandbox Code Playgroud)