有關本文 Microsoft Excel 2000 版本,請參閱213798。
如要Microsoft Excel 98 及較舊版本的 Excel 版本,請參閱149689。
摘要
本文包含範例 Microsoft Visual Basic for Applications程式,您可以使用這些程式處理數種類型的陣列。
其他相關資訊
Microsoft 僅提供圖例的程式設計範例,而不提供明示或隱含的擔保。 這包括但不限於默示的可交易性擔保或適合特定用途的擔保。 本文假設您熟悉所示範的程式設計語言,以及用來建立及偵錯工具的工具。 Microsoft 支援工程師可協助說明特定程式的功能,但他們不會修改這些範例以提供新增功能或建構程式,以滿足您的特定需求。 注意:在Visual Basic for Applications中,單引號 (後) 為批註。
若要填滿陣列,然後將它複製到工作表
-
開啟新活頁簿,然後插入Visual Basic工作表。
-
在模組工作表上輸入下列程式碼。
Sub Sheet_Fill_Array()
Dim myarray As Variant
myarray = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Range("a1:a10").Value = Application.Transpose(myarray)
End Sub -
選取工作表1。
-
在 [工具> 功能表上,指向 [宏,然後按一下 [宏。
-
在 [宏」 對話方塊中,按一下 [Sheet_Fill_Array,然後按一下 [執行。
從工作表中取值並填滿陣列
-
在儲存格 A1:A10 的工作表1 中輸入值。
-
在模組Visual Basic工作表上,輸入下列程式碼:
Sub from_sheet_make_array()
Dim thisarray As Variant
thisarray = Range("a1:a10").Value
counter = 1 'looping structure to look at array
While counter <= UBound(thisarray)
MsgBox thisarray(counter, 1)
counter = counter + 1
Wend
End Sub -
選取工作表1。
-
在 [工具> 功能表上,指向 [宏,然後按一下 [宏。
-
在 [宏」 對話方塊中,按一下 [from_sheet_make_array,然後按一下 [執行。
若要傳遞和接收陣列
-
在模組工作表上,輸入下列程式碼:
Sub pass_array()
Dim thisarray As Variant
thisarray = Selection.Value
receive_array (thisarray)
End Sub
Sub receive_array(thisarray)
counter = 1
While counter <= UBound(thisarray)
MsgBox thisarray(counter, 1)
counter = counter + 1
Wend
End Sub -
選取工作表1,然後強調範圍 A1:A10。
-
在 [工具> 功能表上,指向 [宏,然後按一下 [宏。
-
在 [宏」 對話方塊中,按一下 [pass_array,然後按一下 [執行。
比較兩個數組
-
在工作表1 上建立兩個命名範圍。 命名一個範圍1,另一個範圍2。
例如,將儲存格範圍 A1:A10 高亮,並命名範圍 1;強調儲存格範圍 B1:B10,並命名其範圍 2。 -
在模組工作表上輸入下列程式碼。
Sub compare_two_array()
Dim thisarray As Variant
Dim thatarray As Variant
thisarray = Range("range1").Value
thatarray = Range("range2").Value
counter = 1
While counter <= UBound(thisarray)
x = thisarray(counter, 1)
y = thatarray(counter, 1)
If x = y Then
MsgBox "yes"
Else MsgBox "no"
End If
counter = counter + 1
Wend
End Sub -
選取工作表 2。
-
在 [工具> 功能表上,指向 [宏,然後按一下 [宏。
-
在 [宏」 對話方塊中,按一下 [compare_two_array,然後按一下 [執行。
您每次比較時都會看到一個訊息方塊。
填滿動態陣列
-
在模組工作表上,輸入下列程式碼:
Sub fill_array()
Dim thisarray As Variant
number_of_elements = 3 'number of elements in the array
'must redim below to set size
ReDim thisarray(1 To number_of_elements) As Integer
'resizes this size of the array
counter = 1
fillmeup = 7
For counter = 1 To number_of_elements
thisarray(counter) = fillmeup
Next counter
counter = 1 'this loop shows what was filled in
While counter <= UBound(thisarray)
MsgBox thisarray(counter)
counter = counter + 1
Wend
End Sub -
在 [工具> 功能表上,指向 [宏,然後按一下 [宏。
-
在 [宏」 對話方塊中,按一下 [fill_array,然後按一下 [執行。
注意:變更變數"number_of_elements"會決定陣列的大小。