将Excelstring数组传递给用户定义的VBA函数

我希望使用Excel数组函数来生成一个string数组,然后将其传递给用户定义的函数来去除空格,并连接由","分隔的string。

我有一个函数,当从VBAmacros调用时这样做。 当我尝试使用它作为用户定义的函数,例如=ConcStr({"A","B","C"}) ,我得到一个#Value! 错误。

function如下:

 Sub StrTest() Dim StaticArray(1 To 3) As String Dim Result As String StaticArray(1) = "A" StaticArray(2) = "B" StaticArray(3) = "C" Result = ConcStr(Arr:=StaticArray) MsgBox Result End Sub Function ConcStr(Arr() As String) As String MsgBox "started" Dim N As Long Dim Total As String For N = LBound(Arr) To UBound(Arr) MsgBox Arr(N) Total = Total & "," & Arr(N) Next N ConcStr = Total End Function 

如果你重写你的UDF来接受一个Variant ,它应该可以工作。 另外,你可以使用Join函数来完成你所需要的:

 Function ConcStr(arr As Variant) As String ConcStr = Join(arr, ",") End Function 

声明,调暗,分配和传递数组作为变体。

 Sub StrTest() Dim StaticArray As Variant, Result As String ReDim StaticArray(1 To 3) StaticArray(1) = "A" StaticArray(2) = "B" StaticArray(3) = "C" Result = ConcStr(Arr:=StaticArray) MsgBox Result Result = ConcStr2(Arr:=StaticArray) MsgBox Result End Sub Function ConcStr(Arr As Variant) As String MsgBox "started" Dim N As Long, Total As String For N = LBound(Arr) To UBound(Arr) MsgBox Arr(N) Total = Total & "," & Arr(N) Next N ConcStr = Mid(Total, 2) 'Mid to get rid of the first comma End Function Function ConcStr2(Arr As Variant) As String 'could just be like this, ConcStr2 = Join(Arr, ",") End Function 

我已经添加了一个可选的Join Function版本来简化事物,并用Mid函数修改你的函数来删除前面的逗号。

我能够得到你想要的:

 Public Function ConcatString(ByVal arr As Variant) As String ConcatString = vbNullString Dim i As Long, n As Long, z as Long z = LBound(arr) : n = UBound(arr) For i = z To n ConcatString = ConcatString + arr(i) Next i End Function 

使用