Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 185
For Each-Next constructs
ОглавлениеRecall from the preceding chapter that a collection is a group of related objects. For example, the Workbooks
collection is a collection of all open Workbook
objects. You can also work with many other collections.
Suppose you want to perform some action on all objects in a collection. Or suppose you want to evaluate all objects in a collection and take action under certain conditions. These occasions are perfect for the For Each
-Next
construct because you don't have to know how many elements are in a collection to use the For Each
-Next
construct.
The syntax of the For Each
-Next
construct is as follows:
For Each element In collection [instructions] [Exit For] [instructions] Next [element]
The following procedure uses the For Each
-Next
construct with the Worksheets collection in the active workbook. When you execute the procedure, the MsgBox
function displays each worksheet's Name
property. (If five worksheets are in the active workbook, the MsgBox
function is called five times.)
Sub CountSheets() Dim Item as Worksheet For Each Item In ActiveWorkbook.Worksheets MsgBox Item.Name Next Item End Sub