VBA:将可变数组转换为string

我想使用vba将可变数组转换为string。 我已经尝试了2种方法,但其中没有一种可行,他们似乎都集中在同一点上。

Dim cell As Range Dim val As Variant For Each cell In Range("packing_list[Code]") val = cell.Value Next cell MsgBox Join(val, "//") 

  Dim oSh As Worksheet Dim CodeRange As Variant Set oSh = ActiveSheet CodeRange = oSh.Range("packing_list[Code]").Value MsgBox Join(CodeRange , "//") 

他们都在MsgBox行错误。 我做错了什么?

谢谢

您尝试join的值不是string数组。 连接应该用在数组上

以下是Microsoft说明的链接: https : //msdn.microsoft.com/en-us/library/b65z3h4h%28v=vs.90%29.aspx

他们的例子是:

 Dim TestItem() As String = {"Pickle", "Pineapple", "Papaya"} Dim TestShoppingList As String = Join(TestItem, ", ") 

你的代码应该是这样的:

 Dim i As Integer Dim cell As Range Dim val() As Variant '() indicate it is an array i = 0 For Each cell In Range("packing_list[Code]") ReDim Preserve val(0 to i) As Variant 'must resize array to fit number of items val(i) = cell.Value 'i is the position of the item in the array i = i + 1 'increment i to move to next position Next cell 'Now that you have an array of values (ie ("String1", "String2", ...) instead of just "String" you can: MsgBox Join(val, "//") 

Tranpose可用于为单个列或行生成一维数组或string。

所以对于A1:A10你可以使用

 MsgBox Join(Application.Transpose([a1:a10]), ",") 

要连续工作,你需要第二次Transpose ,所以对于A1:K1

 MsgBox Join(Application.Transpose(Application.Transpose([a1:k1])), ",") 

看起来你认为你的valCodeRangevariables是数组,事实上他们不是。 你已经声明它们是Variants ,但不是Variant Arrays ,我猜你是目标。 添加括号来声明一个variables作为一个数组: Dim CodeRange() as Variant

看到这个: 如何在VBA中声明一个数组variables?

正如@Brandon Keck所说,Join期待一个数组。