如何将参数从 xlwings 传递到 VBA Excel 宏?
How to Pass Arguments from xlwings to VBA Excel Macro?
我正在查看 ,我知道它没有得到完全支持,但我想知道是否有办法做到这一点。
有些喜欢:
from xlwings import Workbook, Application
wb = Workbook(...)
Application(wb).xl_app.Run("your_macro("%Args%")")
这可以通过执行您的建议来完成。但是请记住,此解决方案不会跨平台 (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
Python 示例:
import xlwings as xw
# wb_path = r"set_wb_path"
wb = xw.Book(wb_path)
app = wb.app
variable_to_pass = 'test'
macro = wb.macro(moduleName.macroName)
macro(variable_to_pass)
wb.app.quit()
#or
wb.close()
只要您的 VBA 函数接受一个变量并且您将相同类型的变量 (str,int,list) 传递给它,它就可以工作。
我正在查看
有些喜欢:
from xlwings import Workbook, Application
wb = Workbook(...)
Application(wb).xl_app.Run("your_macro("%Args%")")
这可以通过执行您的建议来完成。但是请记住,此解决方案不会跨平台 (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
Python 示例:
import xlwings as xw
# wb_path = r"set_wb_path"
wb = xw.Book(wb_path)
app = wb.app
variable_to_pass = 'test'
macro = wb.macro(moduleName.macroName)
macro(variable_to_pass)
wb.app.quit()
#or
wb.close()
只要您的 VBA 函数接受一个变量并且您将相同类型的变量 (str,int,list) 传递给它,它就可以工作。