2012-01-26 79 views
7

我想在VBA中,數組列表,所以我必須在Excel VBA中像宣稱的變體:陣列在Excel VBA中

Dim Students(10) as variant 

現在我想存儲在學生列表編號。這些數字並不連續。有時像:

Students(2,7,14,54,33,45,55,59,62,66,69) 

我該如何做到這一點在vba中?我怎樣才能訪問列表項?

回答

10

學生必須聲明爲動態數組。也就是說,一個數組的邊界可以改變。 Dim Students(10)給出了一個數組,其邊界無法更改,無法從數組中加載。

Dim Students() As Variant 

要加載生:

Students = Array(2,7,14,54,33,45,55,59,62,66,69) 

要訪問的元素:

Dim Inx As Long 

For Inx = LBound(Students) to UBound(Students) 
    Debug.Print Students(Inx) 
Next 

LBOUND(下限)和UBound函數意味着對環路調節到元件中的實際數量學生們。

+0

+1幹得好!另請注意,數組默認情況下是零邊界的。 – JimmyPena

+1

@JP。我知道,但不知何故,除非我已明確宣佈下限,我不相信它將始終爲零。 –

3

您可以添加值到一個這樣的數組...

For i = 1 to 10 
    Students(i) = i 
Next i 

或者這樣

Students = Array(2,7,14,54,33,45,55,59,62,66,69) 

然後你就可以在同一個莊園訪問值。請注意,如果您使用第二個選項,則需要聲明如下:

Dim Students() As Variant 
4

這是對你來說太複雜,現在,你可能從來沒有碰到一個情況下,你就需要這樣,而是:

我用更形成內存效率陣列下面的方法(因爲Variant使用任何變量類型的大部分內存),同時仍然可以方便地將數組內容聲明爲一行。按照你的例子:

Dim Students() As Long 
Dim Array2() As String 

Array2() = Split("2,7,14,54,33,45,55,59,62,66,69", ",") 

ReDim Array1(0) As Long 
For Loop1 = LBound(Array2()) To UBound(Array2()) 
    ReDim Preserve Array1(0 To (UBound(Array1) + 1)) As String 
    Array1(Loop1) = Array2(Loop1) 
Next Loop1 
ReDim Preserve Array1(0 To (UBound(Array1) - 1)) As Long 

Erase Array2 

訪問它會是這樣的一個例子:

For Loop1 = LBound(Students) to UBound(Students) 
    Msgbox Students(Loop1) 
Next Loop1 

我得知這個從這裏:http://www.vbforums.com/showthread.php?669265-RESOLVED-VBA-Excel-Assigning-values-to-array-in-a-single-line&p=4116778&viewfull=1#post4116778

+0

請注意,您只需要對非字符串數組執行此操作,因爲對於字符串,您可以簡單地執行'arrStrings()= Split(「Item1,Item2,Item3」,「,」,vbtextcompare)'或其他任何操作。 – puzzlepiece87

0

好, 這取決於你將如何提供該數組的值,你會得到從Worksheet.Range的值TextBoxListB牛,但基本上代碼將是類似的東西:

Dim students(10) as Integer 
Dim Carrier as Integer 
For i = LBound(students) To UBound(Students) 
    'some code to get the values you want to from whatever is your source 
    'then assign the value to Carrier 

    students(i)=Carrier 
Next i 

這是不好的做法暗淡數組爲Variant時,你當然知道,你要只使用整數,因爲它會吃很多的首先不需要的內存。 你也應該知道要分配的數字的範圍,如果它超過整數限制,那麼你應該使用Double或Float。 這是我第一次參與網站,乾杯。