如何从Python传递变量到VBA子程序

5

我是一名有用的助手,可以为您翻译文本。

我正在尝试从我的Python代码中调用一个VBA子程序,将指定文件夹中的所有Excel文件从xls格式转换为xlsm格式。

当我在VBA中没有使用变量时,我可以使用以下代码,并且它工作得很好。

Python 代码:

import os
import win32com.client

xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Users\Name\Documents\PERSONAL.XLSB", ReadOnly=1)
xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal"
xl.Application.Quit() # Comment this out if your excel script closes
del xl

VBA代码:

Public Sub xlstoxlsmFinal()

' goes through all the sub folders of a specified folder and created an xlsm(macro enabled version) of any xls documents


    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    Path = "C:\Users\Name\Documents\Monthly Reports\16.06 Reports\Agent Reports"
    queue.Add fso.GetFolder(Path)

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
                If Right(oFile, 4) <> "xlsm" And Right(oFile, 3) <> "pdf" Then
                Workbooks.Open Filename:=oFile
                ActiveWorkbook.SaveAs Filename:=oFile & "m", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
                ActiveWorkbook.Close
    End If
        Next oFile
    Loop

然而,当我尝试从Python将变量传递到VBA时,无法调用该函数。以下是我目前为止尝试过的方法。

具有变量的Python代码:

import os
import win32com.client

Datev = """16.06 """
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Users\Name\Documents\PERSONAL.XLSB", ReadOnly=1)
xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal(" + Datev + ")")
##    xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function.
xl.Application.Quit() # Comment this out if your excel script closes
del xl

带变量的VBA代码:

Public Sub xlstoxlsmFinal(Datev As String)

' goes through all the sub folders of a specified folder and created an xlsm(macro enabled version) of any xls documents


    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    Path = "C:\Users\Name\Documents\Monthly Reports\" & Datev & "Reports\Agent Reports"
    queue.Add fso.GetFolder(Path)

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
                If Right(oFile, 4) <> "xlsm" And Right(oFile, 3) <> "pdf" Then
                Workbooks.Open Filename:=oFile
                ActiveWorkbook.SaveAs Filename:=oFile & "m", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
                ActiveWorkbook.Close
    End If
        Next oFile
    Loop

当我在Python中运行此代码时,会收到以下错误信息:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'PERSONAL.XLSB!Module1.xlstoxlsmFinal(16.06 )'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)

有没有人知道如何成功地将Python变量传递给VBA子程序?
谢谢!

请查看以下网址中的“返回值…”部分:http://www.rondebruin.nl/win/s9/win001.htm。 - Tim Williams
谢谢,这正是我所需要的。 - walker_4
2个回答

6
根据Tim Williams的建议,我阅读了rondebruin.nl/win/s9/win001.htm的最后一节,并编写了Python代码。
    import os
    import win32com.client

    Datev = """16.06 """
    xl=win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Open(Filename="C:\Users\Name\Documents\PERSONAL.XLSB", ReadOnly=1)
    xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal", Datev)
    xl.Application.Quit() # Comment this out if your excel script closes
    del xl

材料的不同之处在于更改了这行代码:
xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal(" + Datev + ")")

致:

xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal", Datev)

现在代码完美运行!

如何将多个参数传递给 VBA 函数? - SM079

1

前往“开发人员”标签下的宏安全性,选择“启用所有宏”选项


我不知道这是否有助于特定情况,但你尝试过xlwings吗? - Logan Reed
当我在谷歌上搜索时,看到了一些相关的参考资料,也许我会尝试一下。 - walker_4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接