excel vba for each vba for each用法

Step 1 在功能列「開發人員」中程式碼選擇「Visual Basic」

Step 2 以下是For each….Next循環的一般用法以及範例,先定義一個字串陣列(MyArray),然後使用For Each…Next循環取得陣列中每個字串,並使用Debug.Print將結果顯示在即時運算視窗中
For Each element In collection
' 執行操作,element代表陣列中的當前元素,可自行更改名稱
Next element
Sub IterateArray()
Dim MyArray(3) As String
Dim element As Variant
' 設定陣列資料
MyArray(0) = "A"
MyArray(1) = "B"
MyArray(2) = "C"
MyArray(3) = "D"
' 取得陣列中每個元素
For Each element In MyArray
Debug.Print element
Next element
End Sub
【教學】Excel VBA中如何使用For Each…Next?超簡單馬上學會!