2015-12-10 36 views
3

我想將一個變量數組轉換爲使用vba的字符串。 我已經嘗試了2種方法,但其中沒有一種可以工作,它們似乎都集中在同一點上。VBA:將可變數組轉換爲字符串

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線兩種錯誤。我做錯了什麼?

謝謝

+0

嘗試:'CodeRange = Application.Transpose(oSh.Range (「packing_list [Code]」)。Value)' – Rory

+0

我總是先使用一個'Collection',然後在已知的元素的#號中轉換成一個數組。 – ja72

+0

或者只是'MsgBox加入([Transpose(packing_list [Code])],「//」)' – Slai

回答

4

您試圖加入的值不是字符串數組。加入應該要在陣列中使用

這裏是鏈接到微軟說明: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 (i.e. ("String1", "String2", ...) instead of just "String" you can: 

MsgBox Join(val, "//") 
+0

所以解決方法是將「Value」轉換爲字符串,然後將其添加到數組中? –

+0

我可以使用CStr將每個單元格的值轉換爲字符串嗎? –

+0

@Rémi不,你的變量不是數組變量,它只能存儲單個值..我將編輯我的答案,告訴你我的意思 –

0

看起來你認爲你的valCodeRange變量是數組,但實際上它們不是。你已經宣佈他們爲Variants,但不是Variant Arrays,我懷疑你是目標。加上括號來聲明一個變量爲一個數組:Dim CodeRange() as Variant

看到這個: How do I declare an array variable in VBA?

由於@Brandon凱克說,加入期待一個數組。

3

Tranpose可用於爲單個列或行生成一維數組或字符串。

所以對於A1:A10,你可以使用剛剛

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

到你需要第二個Transpose連續工作,所以對於A1:K1

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

已經錯過了Rory早先的建議。 – brettdj