Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 183
With-End With constructs
ОглавлениеThe With
-End With
construct enables you to perform multiple operations on a single object. To start understanding how the With
-End With
construct works, examine the following procedure, which modifies six properties of a selection's formatting. (The selection is assumed to be a Range
object.)
Sub ChangeFont1() Selection.Font.Name = "Cambria" Selection.Font.Bold = True Selection.Font.Italic = True Selection.Font.Size = 12 Selection.Font.Underline = xlUnderlineStyleSingle Selection.Font.ThemeColor = xlThemeColorAccent1 End Sub
You can rewrite this procedure using the With
-End With
construct. The following procedure performs exactly like the preceding one:
Sub ChangeFont2() With Selection.Font .Name = "Cambria" .Bold = True .Italic = True .Size = 12 .Underline = xlUnderlineStyleSingle .ThemeColor = xlThemeColorAccent1 End With End Sub
Some people think that the second incarnation of the procedure is more difficult to read. Remember, though, that the objective is increased speed. Although the first version may be more straightforward and easier to understand, a procedure that uses the With
-End With
construct to change several properties of an object can be faster than the equivalent procedure that explicitly references the object in each statement.