For Each
循環用於為數組或集合中的每個元素執行語句或一組語句。For Each
循環與For
循環類似; 然而,For Each
循環是為數組或組中的每個元素執行的。 因此,這種類型的循環中將不存在步計數器。 它主要用於數組或在文件系統對象的上下文中使用,以便遞歸操作。
語法
以下是VBA中For Each
循環的語法。
For Each element In Group [statement 1] [statement 2] .... [statement n] [Exit For] [statement 11] [statement 22] Next
示例
Private Sub Constant_demo_Click() 'fruits is an array fruits = Array("蘋果", "橙子", "櫻桃") Dim fruitnames As Variant 'iterating using For each loop. For Each Item In fruits fruitnames = fruitnames & Item & Chr(10) Next MsgBox fruitnames End Sub
當執行上面的代碼時,它會在每行中打印一個項目的所有水果名稱。