我在看How do I call an Excel macro from Python using xlwings?,我知道它并不完全支持,但我想知道是否有办法做到这一点。
有些人喜欢:
from xlwings import Workbook, Application
wb = Workbook(...)
Application(wb).xl_app.Run("your_macro("%Args%")")
答案 0 :(得分:4)
这可以通过做你的建议来完成。但请记住,此解决方案不是跨平台的(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)
实施例: 假设您有一个应在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)
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