2012-10-22 17 views
2

我已經發現如何創建一個數組,但我無法輕鬆推送項目。我必須保持一個索引到下一個位置,並且每次我推動一個項目時增加;我無法找到實際定義數組的方法,推送一些值並將它們輸出爲VBA中的字符串? (新陣列,推送,加入)

我還發現有一個漂亮的.Add方法,其行爲與推送方法完全相同。但我如何加入他們呢?全局連接方法不適用於集合。

我在這裏錯過了什麼?任何人都可以幫助我定義一個數組,在沒有索引的情況下輕鬆推送項目,然後將它們輸出到由「,」隔開的字符串?

感謝

回答

10

你不能直接做到這一點。 VBA中的數組通常需要在使用之前進行索引和標註。

您可以使用動態數組和調整分配變量之前:

Dim arr() As String 
ReDim arr(0) 

arr(UBound(arr)) = "Some String" 
ReDim Preserve arr(UBound(arr) + 1) 
arr(UBound(arr)) = "Some Other String" 
ReDim Preserve arr(UBound(arr) + 1) 
arr(UBound(arr)) = "Some 3rd String" 

MsgBox Join(arr, ",") 

的保留關鍵字數組中保持的值,而不是覆蓋它們。通常不推薦使用上述方法,但由於Preserve成本較高,只允許調整數組的最後一個維度。

集合是不同的,是在VBA環境慢,一般不靈活(你還沒說這環境,但我會承擔的Excel)

Dim coll As Collection 
Dim itm As Variant 
Dim tempS As String 


Set coll = New Collection 
coll.Add "Some String" 
coll.Add "Some Other String" 
coll.Add "Some 3rd String" 

For Each itm In coll 
    tempS = tempS & itm & "," 
Next itm 

MsgBox Left(tempS, Len(tempS) - 1) 

你通過他們需要循環構建陣列。

這裏有無數的其他選項根據您的需求

內置方法

字符串,看看分裂:

Const stri As String = "Some String, Some Other String, Some 3rd String" 
Dim arr() As String 

arr = Split(stri, ",") 

MsgBox Join(arr, ",") 

使用外部對象

腳本辭典

Dim dic As Object 

Set dic = CreateObject("scripting.Dictionary") 
dic.Add "1", "Some String" 
dic.Add "2", "Some Other String" 
dic.Add "3", "Some 3rd String" 

Debug.Print Join(dic.items, ",") 

淨ArrayList的

Dim al As Object 

Set al = CreateObject("System.Collections.Arraylist") 
al.Add "Some String" 
al.Add "Some Other String" 
al.Add "Some 3rd String" 

MsgBox Join(al.ToArray(), ",") 
+0

感謝工作。我已經使用了集合,然後創建了一個Join函數來加入集合的項目......很難爲另一個選擇一個答案,但這包含了數組和集合的信息,因此我認爲對其他人更有用尋找這個話題。 –

1

您可以用對於...每個語句通過它使用集合對象,然後循環:

Dim colItems As New Collection 
Dim strOutput As String 

'Add Items to Collection 
colItems.Add "Item 1" 
colItems.Add "Item 2" 
colItems.Add "Item 3" 

'Loop through the collection and place items in strOutput 
For Each Item in colItems 
    If strOutput <> "" Then strOutput = strOutput & "," 
    strOutput = strOutput & Item 
Next 

Msgbox strOutput 

的消息框將讀取Item 1,Item 2,Item3

這行代碼:

If strOutput <> "" Then strOutput = strOutput & "," 

是每一個項目之後添加一個逗號,除了通過所述循環中的第一時間(已添加的任何項之前)。

+0

感謝奏效。我已經使用了該集合,然後創建了一個Join函數來加入集合的項目...我也不知道在每個的「伎倆」,以便只有在項目之間有逗號;) –

相關問題