Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 107

Understanding collections

Оглавление

Many of Excel's objects belong to collections. Your house sits within a neighborhood, for example, which is a collection of houses called a neighborhood. Each neighborhood sits in a collection of neighborhoods called a city. Excel considers collections to be objects themselves.

In each Workbook object, you have a collection of Worksheets. The Worksheets collection is an object that you can call upon through VBA. Each worksheet in your workbook lives in the Worksheets collection.

If you want to refer to a worksheet in the Worksheets collection, you can refer to it by its position in the collection as an index number starting with 1 or by its name as quoted text. If you run these two lines of code in a workbook that has only one worksheet and that worksheet is called MySheet, they both do the same thing:

Worksheets(1).Select Worksheets("MySheet").Select

If you have two worksheets in the active workbook that have the names MySheet and YourSheet, in that order, you can refer to the second worksheet by typing either of these statements:

Worksheets(2).Select Worksheets("YourSheet").Select

If you want to refer to a worksheet in a workbook called MySheet in a particular workbook that is not active, you must qualify the worksheet reference and the workbook reference. Here's an example:

Workbooks("MyData.xlsx").Worksheets("MySheet").Select

Excel 2019 Power Programming with VBA

Подняться наверх