如何将变量从Python传递给VBA Sub

时间:2022-01-06 20:43:05

I am trying to call a VBA sub from my Python code to convert all excel files in a specified folder from the xls to xlsm format.

我试图从我的Python代码调用一个VBA sub来将指定文件夹中的所有excel文件从xls转换为xlsm格式。

I can use the following code when I am not using a variable in the VBA and it works well.

当我在VBA中不使用变量时,我可以使用以下代码,它运行良好。

Python Code:

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 Code:

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

However, I am unable to call the function when I try to pass a variable from python to VBA. Below is what I have tried so far.

但是,当我尝试将变量从python传递到VBA时,我无法调用该函数。以下是我到目前为止所尝试的内容。

Python code with variable:

带变量的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 code with Variable:

带变量的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

When I run this in python I get the error message:

当我在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)

Would anybody know how to succesfully pass a Python variable to a VBA sub?

有人会知道如何成功地将Python变量传递给VBA子吗?

Thanks!

谢谢!

2 个解决方案

#1


3  

Per Tim Williams suggestion I read the last section of rondebruin.nl/win/s9/win001.htm and formulated the python code

Per 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

The material difference was changing the line:

材料差异正在改变这条线:

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

To:

至:

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

Now the code works perfectly!

现在代码完美无缺!

#2


1  

Go to Macro Security under the developer tag and choose the Enable all macros option

转到开发人员标记下的宏安全性,然后选择“启用所有宏”选项

#1


3  

Per Tim Williams suggestion I read the last section of rondebruin.nl/win/s9/win001.htm and formulated the python code

Per 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

The material difference was changing the line:

材料差异正在改变这条线:

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

To:

至:

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

Now the code works perfectly!

现在代码完美无缺!

#2


1  

Go to Macro Security under the developer tag and choose the Enable all macros option

转到开发人员标记下的宏安全性,然后选择“启用所有宏”选项