【问题标题】:Passing arrays from VBA to Python (And back again)将数组从 VBA 传递到 Python(然后再返回)
【发布时间】:2023-01-25 19:55:02
【问题描述】:

我想从 VBA 向 python 发送一个十进制数数组并返回一组。目前我可以从 VBA 宏运行 python 脚本并向它传递字符串参数,但我不能发送数组。

我已经研究过其他方法来做到这一点,但似乎无法找到任何其他方法。此外,我正在尝试远离付费软件,如 PyXll 或类似软件。

我比 Python 更熟悉 VBA,所以我更喜欢在 Python 中工作,只使用 VBA 发送和接收 CSV 文件的数据 这是我到目前为止所得到的,


    Pythonexe = """C:\ ~~~ \python.exe""" 'path of the python.exe
    PythonScript = """C:\ ~~~ \ExcelToPython.py""" 'path of the Python script

    Dim ColumnLength As Integer
    Dim RowLength As Integer
    Dim counter As Integer

    counter = 0
    
    
    
    For RowLength = 0 To 10
        For ColumnLength = RowCounter
        
            PythonArg(counter) = (ThisWorkbook.Worksheets("location sort").Cells(ColumnLength, RowLength))
            counter = counter + 1
            
        Next ColumnLength

        objShell.Run Pythonexe & PythonScript & PythonArg
        counter = 0
        
    Next RowLength 

我试图让这个尽可能简单,因为我将在几台不同的机器上运行。 任何帮助,将不胜感激。

【问题讨论】:

    标签: python arrays excel vba


    【解决方案1】:

    将十进制数数组从 VBA 传递到 Python 的一种方法是将数组转换为字符串,然后将该字符串作为参数传递给 Python 脚本。在 Python 中,您可以将字符串转换回数字数组。

    下面是如何在 VBA 中执行此操作的示例:

    'Convert the array to a string
    PythonArg = Join(PythonArray, ",")
    'Pass the string as an argument to the Python script
    objShell.Run Pythonexe & " " & PythonScript & " " & PythonArg
    

    在 Python 中,您可以使用 ast.literal_eval() 函数将字符串转换回数字数组。

    import ast
    import sys
    
    # Get the array as a string from the command line arguments
    array_string = sys.argv[1]
    # Convert the string to an array of numbers
    array = ast.literal_eval(array_string)
    print(array)
    

    您还可以使用 numpy 数组和 json 库将数组转换为字符串,然后在 python 中将其转换回数组

    import numpy as np
    import json
    PythonArg = json.dumps(np.array(PythonArray))
    
    
    import numpy as np
    import json
    array = json.loads(sys.argv[1])
    array = np.array(array)
    

    值得注意的是,此方法有一个限制,即可以在命令行中传递的字符串的最大大小,因此如果超过限制,您可能需要将数组拆分为更小的块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 2017-05-05
      • 2020-01-05
      • 2011-01-15
      • 2014-02-07
      • 2016-05-17
      相关资源
      最近更新 更多