可以返回对象和标量的vba函数

时间:2019-01-10 23:59:14

标签: excel vba function return

我正在尝试在Excel中编写一个vba函数,该函数可以传递对象和标量类型。我可以使用Variant作为签名来使函数正常工作,但是,由于对象需要“设置”而标量不需要它,因此无法从调用它的位置获取返回值。我在下面编写了以下测试用例。有人可以帮我使它正常工作吗?

我正在开发自己的JSON类模块版本。为了“加载”外部数据,我有一个使用递归函数的阅读器,需要这样做(如果您想知道的话)。

编辑:我不能像QHarr建议的那样两次调用该函数。 QHarr方法确实适用于下面的代码,但是,这不是完整的代码,只是一个示例。有两个原因,1)函数读取外部数据并两次调用将丢失正在读取的当前行,并且2)实际函数是递归的,因此像这样调用它会导致无法预测的方式。

Sub test_passing_scalars_and_objects()

    Dim i As Long
    Dim var As Variant

    For i = 0 To 3

        Set var = pass_it(i)
        Debug.Print "cleared index:=" & i

    Next i

End Sub

Function pass_it(ByVal val As Long) As Variant

    Dim d As New Scripting.Dictionary
    Dim c As New Collection
    Dim arr() As Variant

    Select Case val
        Case Is = 0 ' dictionary
            d.Add "101", 101
            d.Add "202", 202
            Set pass_it = d

        Case Is = 1 ' collection
            c.Add "101"
            c.Add "202"
            Set pass_it = c

        Case Is = 2 ' array
            ReDim arr(1)
            arr(0) = "101"
            arr(1) = "202"
            pass_it = arr

        Case Is = 3 ' scalar
            pass_it = "101"
    End Select

End Function

1 个答案:

答案 0 :(得分:3)

您可以返回一个带有布尔值的数组,该数组指示是否为Object(因为仅调用一次,所以不允许使用IsObject)。

Option Explicit
Public Sub test_passing_scalars_and_objects()
    Dim i As Long, var As Variant
    For i = 0 To 3
        var = pass_it(i)
        If var(0) Then
            Set var = var(1)
        Else
            var = var(1)
        End If
        Debug.Print "cleared index:=" & i
    Next i
End Sub

Public Function pass_it(ByVal val As Long) As Variant
    Dim d As New Scripting.Dictionary, c As New Collection, arr() As Variant

    Select Case val
        Case Is = 0 ' dictionary
            d.Add "101", 101
            d.Add "202", 202
            pass_it = Array(True, d)

        Case Is = 1 ' collection
            c.Add "101"
            c.Add "202"
             pass_it = Array(True, c)

        Case Is = 2 ' array
            ReDim arr(1)
            arr(0) = "101"
            arr(1) = "202"
            pass_it = Array(False, arr)

        Case Is = 3 ' scalar
            pass_it = Array(False, "101")
    End Select
End Function