如何将作为字符串数组的单元格内容传递给函数作为参数?

时间:2019-07-15 23:52:31

标签: arrays excel vba arguments

我有这个VBA UDF,可以正确地返回一个字符串数组:

Function SplitString(ByVal Str As String, ByVal StrLen As Integer) As String()
    Dim ArrStrs() As String
    Dim ArrCount As Integer
    ReDim ArrStrs((Len(Str) - 1) \ StrLen)
    ArrCount = 0
    For i = 1 To Len(Str) Step StrLen
        ArrStrs(ArrCount) = Mid(Str, i, StrLen)
        ArrCount = ArrCount + 1
    Next

    SplitString = ArrStrs
End Function

我在Excel工作表的单元格中使用了上述功能,例如单元格A1

=SplitString("wordexample";2)

哪个节目

enter image description here

然后,进入单元格的编辑模式并单击F9,它将显示

enter image description here

现在,我想将A1的内容作为名为ArrayOfStrs的参数传递给另一个UDF。

我尝试了这些以及其他一些方法

Function MyFunct(ArrayOfStrs As Variant, ParamArray CStrs() As Variant)
'Using Function MyFunct(ArrayOfStrs As String, ParamArray CStrs() As Variant) I get #VALUE! error

    MsgBox ArrayOfStrs(1)   'returns "wo"
    'MsgBox ArrayOfStrs(2)   returns ""
    'MsgBox ArrayOfStrs(...) returns ""

End Function

但是我无法获得ArrayOfStrs作为字符串数组。也就是说,似乎只有先前拆分的字符串的第一个值(wo)被传递给MyFunct。实际上,只有ArrayOfStrs(1)有效(它返回wo),其他值(rdexampl和{ {1}})在e中似乎不可用。

如何正确地将ArrayOfStrs传递给ArrayOfStrs作为函数参数?

1 个答案:

答案 0 :(得分:4)

您可以Evaluate的内容A1,其中A1包含问题中提到的公式:

Function myFunct(myRange As Range)
    Dim ArrayOfStrs As Variant
    Dim msg As String
    Dim I As Long
ArrayOfStrs = Evaluate(myRange.Formula)

msg = ""
For I = LBound(ArrayOfStrs) To UBound(ArrayOfStrs)
    msg = msg & vbLf & ArrayOfStrs(I)
Next I

msg = Mid(msg, 2)

MsgBox msg

End Function

但是无需将SplitString放在工作表上即可得到结果:

Function myFunct2()
    Dim arr As Variant
    Dim I As Long
    Dim msg As String

arr = SplitString("wordexample", 2)
msg = ""
For I = LBound(arr) To UBound(arr)
    msg = msg & vbLf & arr(I)
Next I

msg = Mid(msg, 2)

MsgBox msg

End Function

enter image description here