我有一个子类,它接受以用户形式生成的变量数组,我想提取所有值并将它们作为单个逗号分隔的字符串返回。这可能很基本,但是我很难将数组中的值转换为字符串。尝试将变体强制转换为字符串时,出现类型不匹配的情况。知道我在做什么错吗?
Sub formSearch(ParamArray search() As Variant)
Dim returnString As String
returnString = ""
For i = LBound(search) To UBound(search)
returnString = returnString + CStr(search(i)) + ","
Next
MsgBox returnString
End Sub
答案 0 :(得分:0)
我遇到了同样的问题,因为输入数组是WorkSheet上NamedRange的内容。
即使NamedRange是单元格的单列,VBA返回的数组也是值的二维数组,因此代码需要 i,1 调整CStr函数以使其起作用:
Function getCellArrayAsString(RangeName As String) As String
Dim arr() As Variant
getCellArrayAsString = ""
arr = ThisWorkbook.Names(RangeName).RefersToRange.value
For i = LBound(arr) + 1 To UBound(arr)
getCellArrayAsString = getCellArrayAsString & CStr(arr(i, 1)) & ","
Next
End Function
或将其应用于OP的代码:
Sub formSearch(ParamArray search() As Variant)
Dim returnString As String
returnString = ""
For i = LBound(search) To UBound(search)
returnString = returnString + CStr(search(i,1)) + ","
Next
MsgBox returnString
End Sub
我怀疑您的代码遇到了同样的问题,因为您的输入实际上是二维数组。