从电子表格调用 VBA 自定义类型的 returns 函数

Call VBA function that returns custom type from spreadsheet

我有一个 vba 函数,它 returns 自定义数据类型,定义为:

Public Type stockValue
        stock As String
        value As Double
End Type

我的问题是,当我从电子表格单元格调用该函数时,我该如何处理这个问题?例如,假设我希望单元格显示 stock 值,我尝试了 =function().stock 但它不起作用

感谢任何帮助,谢谢!

Function getLowestPnl(strat As String, rank As Integer) As stockValue

    Call Conecta_DB(conexao)
    Set registros = New ADODB.Recordset

    strSQL = "SELECT stock,sum([value]) FROM Reports.dbo.Entry WHERE idStrategy='" & strat & "' and idType=1 GROUP BY stock  ORDER BY sum([value])"
    'strSQL = "SELECT [finance],[sales],[management],[research],[administration] FROM [COS].[dbo].[Complementarity] WHERE [idCompany] =" & idCompany & " and [year]=" & year & " and [CEO]=1"

    registros.Open strSQL, conexao, adOpenStatic, adLockOptimistic

    parar = False
    If Not registros.EOF Then

        x = registros.GetRows()
        i = 0
        Do While parar <> True

            If i = (rank - 1) Then
                getLargestShortExp.stock = Trim(x(0, i))
                getLargestShortExp.value = x(1, i)
                parar = True
            End If
            i = i + 1
        Loop

    End If

    registros.Close
    getLowestPnl = ret
End Function

您只能return Excel 从用户定义函数中理解的数据类型。 Excel 不理解自定义数据类型。

相反,您必须 return 一个变体数组,其中包含来自您的自定义数据类型的 2 个值。然后,您可以将函数数组输入到 2 个单元格中,或者使用另一个函数(例如 INDEX)从 returned 数组中检索您想要的值。

您可以执行以下操作:

Type XYDouble
    X As Double
    Y As Double
End Type

Private Function Compute(ByVal X As Double, ByVal Y As Double) As XYDouble
    Compute.X = ....
    Compute.Y = ...
End Function


Function ComputeX(ByVal X As Double, ByVal Y As Double) As Double
    ComputeX = Compute(X, Y).X
End Function

Function ComputeY(ByVal X As Double, ByVal Y As Double) As Double
    ComputeY = Compute(X, Y).Y
End Function

并且,您可以使用以下公式获取单元格中的 X(或 Y)值:“=ComputeX(C7;D7)”