摘要
本文包含您可以用來處理數種陣列的 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 的 Sheet1 上輸入值。
-
在 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],然後按一下 [執行]。
比較兩個數組
-
在 Sheet1 上建立兩個具名範圍。 命名一個 range1,另一個範圍2。
例如,醒目提示 A1:A10 儲存格範圍,並將它命名為 range1;醒目提示儲存格範圍 B1:B10,並將它命名為 range2。 -
在模組工作表上輸入下列程式碼。
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」將會決定陣列的大小。