我希望使用Excel数组函数生成一个字符串数组,然后将其传递给用户定义的函数以剥离空白并连接由","
分隔的字符串。
我有一个从VBA宏调用时执行此操作的函数。当我尝试将它用作用户定义的函数时,例如=ConcStr({"A","B","C"})
,我收到#Value!
错误。
功能如下:
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
答案 0 :(得分:1)
如果您重写UDF以接受Variant
,它应该可以正常工作。此外,您只需使用Join
功能即可完成所需操作:
Function ConcStr(arr As Variant) As String
ConcStr = Join(arr, ",")
End Function
答案 1 :(得分:0)
我能够得到你想要的东西:
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
答案 2 :(得分:0)
声明,调暗,分配并将数组作为变体传递。
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 function修改您的函数以删除前导逗号。