简体   繁体   English

从Python调用Excel用户定义的函数总是返回None

[英]Calling an Excel user defined function from Python always returns None

I'm trying to get the return value from an Excel function that i called from a python. 我试图从我从python调用的Excel函数中获取返回值。 I always get a None value. 我总是得到None值。

Here is the excel function : 这是excel函数:

Public Function GetString()
    GetString = "aa"
End Function

And Here is the call : 这是电话:

xlApp.Run('ThisWorkbook.GetString')

Returned : None 返回: None

I have no problem getting in the specified function since I tried to modify a cell value from it and it worked. 我可以从指定的函数中修改单元格值,并且可以正常工作,因此可以轻松进入指定函数。

Am I missing anything ? 我有什么想念的吗?

It is not clear how you assigned your variable xlApp . 目前尚不清楚如何分配变量xlApp Assuming code like 假设像

import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
xlApp = xlApp.Application

consider: 考虑:

  1. You have to assign the result to a variable, as in 您必须将结果分配给变量,如

    myStr = xlApp.Run('ThisWorkbook.GetString')

  2. You seem to have placed the user defined function in ThisWorkbook , in the Excel file. 您似乎已将用户定义的函数放置在Excel文件的ThisWorkbook中。 Unless this is intentional, open the Excel file, insert a Module in the Visual Basic Editor, and move there your Function. 除非故意这样做,否则请打开Excel文件,在Visual Basic编辑器中插入一个模块,然后将函数移到那里。 Modify your call from Python accordingly. 相应地修改来自Python的调用。

  3. You may want to define the function as 您可能需要将函数定义为

    Public Function GetString() as String

See How to call Excel VBA functions and subs using Python win32com? 请参见如何使用Python win32com调用Excel VBA函数和子函数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM