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

时间:2015-04-27 19:49:18

标签: excel vba excel-vba spreadsheet

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

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

2 个答案:

答案 0 :(得分:4)

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

相反,您必须返回包含自定义数据类型中的2个值的变量数组。然后你要么将数组输入2个单元格,要么使用INDEX等其他函数从返回的数组中检索你想要的值。

答案 1 :(得分:0)

您可以执行以下操作:

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)”