如何从 xlwings 调用 Excel 函数

How to call an Excel function from xlwings

如何直接从 xlwings 调用 Excel 函数(如 sumaverageproducttext)?

临时解决方案:

我能想出的唯一方法是制作一本帮助 Excel 的书,并为 xlwings 提供以下 UDF 样板文件:

'Some extreme workarounds to get excel-like functions working ~95%
'This function is partly generated from a Python script
Public Function xlFunction(fName As String, _
                           Optional args As Collection = Nothing) As Variant
    If args Is Nothing Then
        Set args = New Collection
    End If
    
    'First try with Application.WorksheetFunction object
    On Error GoTo handleWSError
    Select Case args.Count
    
    Case 0
        xlFunction = CallByName(Application.WorksheetFunction, fName, VbGet)
    
    Case 1
        xlFunction = CallByName(Application.WorksheetFunction, fName, VbGet, args(1))

    Case 2
        xlFunction = CallByName(Application.WorksheetFunction, fName, VbGet, args(1), args(2))

    '... Case 3 to 29 left out 

    Case 30
        xlFunction = callByName(application.worksheetFunction, fName, vbGet, args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11), args(12), args(13), args(14), args(15), args(16), args(17), args(18), args(19), args(20), args(21), args(22), args(23), args(24), args(25), args(26), args(27), args(28), args(29), args(30))
    
    End Select
    
    Exit Function
    
handleWSError:
        'Put some effort into a nice message
        Dim formula As String
        formula = fName & "("
        Dim x As Variant
        
        For Each x In args
            formula = formula & argify(x) & ","
        Next x
        If endsWith(formula, ",") Then
            formula = Mid(formula, 1, Len(formula) - 1)
        End If
        formula = formula & ")"
        
        
        If err.number = 1004 Then
            err.raise err.number, err.source, "Error in Arguments: " & formula, err.helpFile, err.helpContext
        ElseIf err.number = 438 Then
            err.raise err.number, err.source, "No VBA equivalent in Application.WorksheetFunction for " & fName & ": " & formula, err.helpFile, err.helpContext
        Else
            err.raise err.number, err.source, "Error: " & formula & vbCrLf & err.description, err.helpFile, err.helpContext
        End If

End Function

由于当前未在本机 xlwings API 中实现,您必须通过 api 属性使用底层 pywin32 对象,请参阅:https://docs.xlwings.org/en/stable/missing_features.html

在你的情况下,类似这样的事情会起作用(建立在快速入门代码的基础上):

import xlwings as xw

def main():
    wb = xw.Book.caller()
    sheet = wb.sheets[0]
    sheet["A10"].value = wb.app.api.WorksheetFunction.Min(sheet['A1:B2'].api)