[英]Passing Excel string array to user defined VBA function
我希望使用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
如果您改寫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函數修改了您的函數以刪除前導逗號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.