Excel vba with внутри with

Содержание

  1. С оператором
  2. Синтаксис
  3. Замечания
  4. Пример
  5. См. также
  6. Поддержка и обратная связь
  7. Оператор With. End With (Visual Basic)
  8. Синтаксис
  9. Компоненты
  10. Комментарии
  11. Пример 1
  12. Пример 2
  13. VBA With
  14. With Statement in Excel VBA
  15. How to Use With Statement in Excel VBA?
  16. Example #1
  17. Example #2
  18. Example #3
  19. Things to Remember
  20. Recommended Articles
  21. VBA With Statement (With – End With)
  22. Key Points
  23. What is VBA With Statement
  24. Syntax of VBA With Statement
  25. Example to understand the VBA With Statement
  26. Nested With Statement

С оператором

Выполняет последовательность операторов для отдельного объекта или пользовательского типа.

Синтаксис

Withobject [ statements ] End With

Синтаксис оператора With состоит из следующих частей:

Part Описание
object Обязательно. Имя объекта или пользовательского типа.
Операторы Необязательный параметр. Один или несколько операторов, которые выполняются в отношении объекта объект.

Замечания

Оператор With позволяет выполнить последовательность операторов в отношении заданного объекта без повторной квалификации его имени. Например, чтобы изменить несколько свойств одного объекта, поместите операторы присваивания свойств в управляющую структуру With, которая ссылается на объекта; в этом случае вам не понадобится указывать ссылку на объект при каждом присваивании.

В следующем примере демонстрируется использование оператора With для присвоения значений нескольким свойствам одного объекта.

После входа в блок With элемент объект нельзя изменить. Соответственно, вы не можете использовать один оператор With для изменения нескольких объектов.

Вы можете вкладывать операторы With в другие структуры With. Тем не менее, поскольку элементы внешних блоков With маскируются во внутренних блоках With, во внутреннем блоке With необходимо указывать полную ссылку на любой элемент объекта во внешнем блоке With.

В общем случае не рекомендуется использовать переходы в блоки With или из них. Если выполнены операторы в блоке With, однако оператор With или End With остался невыполненным, после выхода из процедуры временная переменная со ссылкой на объект останется в памяти.

Пример

В этом примере используется оператор With для выполнения последовательности операторов в отношении одного объекта. Объект и его свойства являются универсальными именами, используемыми только в целях иллюстрации.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Оператор With. End With (Visual Basic)

Выполняет последовательность операторов, которые многократно ссылаются на единственный объект или структуру, чтобы операторы могли использовать упрощенный синтаксис доступ к членам объекта или структуры. При использовании структуры можно только считывать значения членов или вызвать методы. При попытке присвоения значений членам структуры, используемым в операторе With. End With , возникает ошибка.

Синтаксис

Компоненты

Термин Определение
objectExpression Обязательный. Выражение, результатом которого является объект. Выражение может быть произвольно сложным и вычисляется только один раз. Результатом выражения могут быть данные любого типа, включая простейшие типы.
statements Необязательный элемент. Один или несколько операторов между With и End With , которые могут ссылаться на члены объекта, создаваемого при вычислении выражения objectExpression .
End With Обязательный элемент. Завершает определение блока With .

Комментарии

С помощью With. End With можно выполнять последовательность операторов с указанным объектом без необходимости многократного указания имени объекта. В блоке операторов With члены объекта можно указывать начиная с точки, как если бы перед ней стоял объект оператора With .

Например, чтобы изменить несколько свойств одного объекта, поместите операторы присваивания свойств внутрь блока With. End With и укажите объект лишь один раз, а не по одному разу для каждого свойства.

Если код обращается к одному и тому же объекту в нескольких операторах, оператор With обеспечивает следующие преимущества:

Не требуется многократно вычислять сложное выражение или присваивать результат временной переменной, чтобы несколько раз сослаться на членов объекта.

За счет исключения повторяющихся определяющих выражений код становится более понятным.

Тип данных у objectExpression может быть любым типом класса или структуры или даже простейшим типом Visual Basic (например Integer ). При результат вычисления выражения objectExpression не является объектом, можно только считывать значения его членов или вызвать методы. При попытке присвоения значений членам структуры, используемым в операторе With. End With , возникает ошибка. Это та же самая ошибка, которая возникает, если сразу после вызова метода, возвращающего структуру, попытаться обратиться к члену результата функции и присвоить ему значение, например GetAPoint().x = 1 . Проблема в обоих случаях заключается в том, что структура существует только в стеке вызовов, и в таких ситуациях измененный член структуры не может записывать данные в расположение таким образом, чтобы любой другой код в программе наблюдал за изменениями.

Выражение objectExpression вычисляется один раз при входе в блок. Переназначение выражения objectExpression изнутри блока With невозможно.

Внутри блока With к методам и свойствам только указанного объекта можно обращаться без их полного описания. Можно использовать методы и свойства других объектов, однако необходимо полностью указывать их имена.

Оператор With. End With можно разместить внутри другого такого оператора. Вложенные операторы With. End With могут быть сложны для понимания, если указываемые объекты не очевидны из контекста. Необходимо указывать полную ссылку на объект, находящийся во внешнем блоке With , при ссылке на него из внутреннего блока With .

Переходы внутрь блока операторов With из другой части программы запрещены.

Если блок не содержит цикла, операторы выполняются только один раз. Возможно вложение структур управления различных типов. Дополнительные сведения см. в разделе Вложенные структуры элементов управления.

Ключевое слово With можно также использовать в инициализаторах объектов. Дополнительные сведения и примеры см. в разделах Инициализаторы объектов: именованные и анонимные типы и Анонимные типы.

Если блок With используется исключительно для инициализации свойств или полей только что созданного экземпляра объекта, рекомендуется использовать для этой цели инициализатор объекта.

Пример 1

В следующем примере в каждом блоке With выполняется несколько операторов для одного объекта.

Пример 2

В следующем примере показаны вложенные операторы With…End With : Во вложенном операторе With этот синтаксис относится к внутреннему объекту.

Источник

VBA With

With Statement in Excel VBA

A With statement is used in VBA to access all the properties and methods of a mentioned object. Therefore, we need to supply which VBA object VBA Object The “Object Required” error, also known as Error 424, is a VBA run-time error that occurs when you provide an invalid object, i.e., one that is not available in VBA’s object hierarchy. read more we are referring to first, close the With statement with End With, then inside this statement. Then, we can perform all the property changes and methods of the mentioned object.

Table of contents

Below is the syntax of With Statement in VBA.

The object is nothing but a range of cells or cells we are referring to, and then we can change the properties and perform all the methods associated with that specific cell or cell.

How to Use With Statement in Excel VBA?

Below are some examples of using With statements in Excel VBA.

Example #1

Assume you have a certain value in the A1 cell. We have entered the text as “Excel VBA” in cell A1.

Code:

Now, we access this cell’s “font” property to change the font size.

Under the FONT property, we access the Size property and enter size by putting an equal sign.

Code:

Now similarly, we do other formatting tasks, as shown below.

Code:

It will do all the mentioned tasks, but if you look at the code to perform every formatting activity. We have supplied the cell address every time. It makes the code look lengthy and time-consuming.

Now, we will use VBA With a statement to reduce the entry of cell addresses every time. Open WITH statement in Excel VBA and supply cell address.

Code:

Inside the With statement, put a dot to see all the properties and methods of cell A1.

The first formatting activity is changing font size, so access FONT. Under this, access the SIZE property.

Code:

Similarly, supply other formatting codes and close VBA With statement.

Code:

Run the code to see all the formatting in the mentioned object, i.e., cell A1.

So, all the formatting applies to the cell. Look how cool this technique is.

Example #2

If you want to change all the properties related to the font, you can mention the cell and FONT property.

Code:

Inside the VBA With Statement, we can see the IntelliSense list. It will show properties and methods related to FONT property only.

We can perform any set of activities with this now.

Code:

It will show the result of this below.

Example #3

The below code will access only cell border-related properties.

Code:

The result of this code is as follows.

Things to Remember

  • A With statement is used to minimize the code.
  • We need to supply the object first for the With statement.
  • Once we supply the specific object, we can access only that object’s properties and methods.

Recommended Articles

This article has been a guide to VBA With. Here, we discuss how to use With…End With Statement in Excel VBA along with examples and downloadable Excel sheet. You can learn more about VBA from the following articles: –

Источник

VBA With Statement (With – End With)

Key Points

  • Use the VBA With Statement to minimize the code.
  • You can use a single object at a time while using the With Statement.

What is VBA With Statement

VBA With is a statement to specify an object for once and then run multiple statements for it. In simple words, by using the “WITH” statement to specify an object, and after that, you can access all the properties and methods in one go. It starts with the “With” and ends with “End With”.

Syntax of VBA With Statement

Following is the syntax that you need to use for using With statement in VBA:

  1. With: It’s the starting keyword for the statement that tells VBA that you are specifying the object mentioned.
  2. Object: Here, you need to specify the object that you want to use.
  3. Statement: A statement(s) that you want to run with the specified object.
  4. End With: It’s the ending keyword for the statement.

Example to understand the VBA With Statement

Let’s take an example to understand with the statement in depth. Let’s say you want to change, the font color, size, and font name of cell A1. For doing all these three things you need to access three different properties of VBA font and the code would be:

But here we going to use the With Statement instead of the above code. To use the VBA With Statement, you can use the following steps:

  1. First, type the keyboard “With”.
  2. After that, use the VBA Range to specify the cell A1 with using the font object to specify the font object.
  3. Next, you need to enter the code for all three properties and the values that you want to apply.
  4. In the end, use the keyword “End With” to end the statement.

Here’s the code that you have just written.

Now let’s have a look at both codes and try to understand what is the difference that we have got by using the “With” statement.

In the first code, you have used the font object three times and then further used the property that you want to access and want to make changes to it.

But in the second code, you have used the With statement and specified the font object at once. And then three lines of code within the “With” statement to access all three properties.

When you use the “With” statement and specify an object, it tells VBA that all the statements that you have written need to run with the object mentioned. It not only gives you a structured code but also makes a macro run faster and gives it greater efficiency.

Nested With Statement

I told you in the starting that you can only specify a single object to use the With statement. But there is a way to use more than one or even multiple objects with it. That’s by using VBA LOOPS, and we are going to use FOR EACH LOOP to loop through multiple objects and use the “With”.

Let me tell you an example; you need to loop through all the worksheets and do apply all the following things to all the cells in each worksheet.

  • Font Size: 16
  • Font: Verdena

And in the workbook, you have five worksheets, as I have in the following example:

Use the following steps to write a nested “With” statement.

  1. First, you need to declare a variable to use a worksheet object.
  2. After that, as I said, you need to use For Each Loop. So, you need to write a code with the loop that can loop through all the worksheets.
  3. Now, enter the with statement which can apply font setting that we have discussed above. For referrring to all the cells in the worksheet you can use the “Cells” while specifing the object.

Here’s the full code that you have just written.

Источник

Применение оператора With для упрощения кода VBA Excel и ускорения его работы. Синтаксис оператора With, параметры, поясняющие примеры.

Оператор With предназначен для выполнения последовательности операторов (строк кода) для отдельного объекта или пользовательского типа данных.

Применение оператора With упрощает написание и восприятие кода VBA Excel, а также ускоряет его работу.

Синтаксис

Синтаксис оператора With в VBA Excel:

With object

[statements]

End With

Параметры

Параметры оператора With:

Параметр Описание
object Имя объекта или пользовательского типа данных.
statements Один или несколько операторов (строк кода), которые выполняются в отношении указанного объекта.

Примеры

В следующей процедуре выполняется несколько идущих подряд операторов (строк кода) в отношении одного и того же объекта Range("A1:E5"):

Sub Primer1()

    Range(«A1:E5»).Value = «Тест»

    Range(«A1:E5»).Interior.Color = vbMagenta

    Range(«A1:E5»).Font.Size = 14

    Range(«A1:E5»).Font.Color = vbYellow

    Range(«A1:E5»).Font.Italic = True

    Range(«A1:E5»).Borders.LineStyle = True

End Sub

Если в процедуре выполняется несколько идущих подряд операторов в отношении одного и того же объекта, то оператор With позволяет указать объект только один раз:

Sub Primer2()

    With Range(«A1:E5»)

        .Value = «Тест»

        .Interior.Color = vbMagenta

        .Font.Size = 14

        .Font.Color = vbYellow

        .Font.Italic = True

        .Borders.LineStyle = True

    End With

End Sub

Такое написание кода делает его более понятным, а выполнение – более быстрым.

Конструкции с оператором With можно вкладывать одну в другую:

Sub Primer3()

    With Range(«A1:E5»)

        .Value = «Тест»

        .Interior.Color = vbMagenta

            With .Font

                .Size = 14

                .Color = vbYellow

                .Italic = True

            End With

        .Borders.LineStyle = True

    End With

End Sub

Такой код удобен, когда необходимо выполнить ряд операторов по отношению к некоторому объекту [Range("A1:E5")], а также по отношению к одному из содержащихся в нем объектов [Range("A1:E5").Font].

Примечания

Примечания от разработчика:

  • После входа в блок With параметр object изменить нельзя. Следовательно, один оператор With не может быть использован для изменения нескольких объектов.
  • Во вложенном блоке With необходимо указывать полные ссылки на любые элементы объекта из внешнего блока With.
  • Не рекомендуется использовать переходы в блоки With или из них.

Home / VBA / VBA With Statement (With – End With)

Key Points

  • Use the VBA With Statement to minimize the code.
  • You can use a single object at a time while using the With Statement.

What is VBA With Statement

VBA With is a statement to specify an object for once and then run multiple statements for it. In simple words, by using the “WITH” statement to specify an object, and after that, you can access all the properties and methods in one go. It starts with the “With” and ends with “End With”.

Syntax of VBA With Statement

Following is the syntax that you need to use for using With statement in VBA:

With [OBJECT]
      [Statement]
End With
  1. With: It’s the starting keyword for the statement that tells VBA that you are specifying the object mentioned.
  2. Object: Here, you need to specify the object that you want to use.
  3. Statement: A statement(s) that you want to run with the specified object.
  4. End With: It’s the ending keyword for the statement.

Example to understand the VBA With Statement

Let’s take an example to understand with the statement in depth. Let’s say you want to change, the font color, size, and font name of cell A1. For doing all these three things you need to access three different properties of VBA font and the code would be:

Range("A1").Font.Color = RGB(0, 0, 255)
Range("A1").Font.Size = 16
Range("A1").Font.Name = "Consolas"

But here we going to use the With Statement instead of the above code. To use the VBA With Statement, you can use the following steps:

  1. First, type the keyboard “With”.
  2. After that, use the VBA Range to specify the cell A1 with using the font object to specify the font object.
    2-use-the-vba-range
  3. Next, you need to enter the code for all three properties and the values that you want to apply.
    3-code-for-all-three-properties
  4. In the end, use the keyword “End With” to end the statement.
    4-end-with-to-end-the-statement

Here’s the code that you have just written.

Sub MyMacro()

With Range("A1").Font
        .Color = RGB(0, 0, 255)
        .Size = 16
        .Name = "Consolas"       
End With

End Sub

Now let’s have a look at both codes and try to understand what is the difference that we have got by using the “With” statement.

In the first code, you have used the font object three times and then further used the property that you want to access and want to make changes to it.

But in the second code, you have used the With statement and specified the font object at once. And then three lines of code within the “With” statement to access all three properties.

When you use the “With” statement and specify an object, it tells VBA that all the statements that you have written need to run with the object mentioned. It not only gives you a structured code but also makes a macro run faster and gives it greater efficiency.

Nested With Statement

I told you in the starting that you can only specify a single object to use the With statement. But there is a way to use more than one or even multiple objects with it. That’s by using VBA LOOPS, and we are going to use FOR EACH LOOP to loop through multiple objects and use the “With”.

Let me tell you an example; you need to loop through all the worksheets and do apply all the following things to all the cells in each worksheet.

  • Font Size: 16
  • Font: Verdena

And in the workbook, you have five worksheets, as I have in the following example:

Use the following steps to write a nested “With” statement.

  1. First, you need to declare a variable to use a worksheet object.
    7-steps-to-write-nested
  2. After that, as I said, you need to use For Each Loop. So, you need to write a code with the loop that can loop through all the worksheets.
    8-write-code-with-the-loop
  3. Now, enter the with statement which can apply font setting that we have discussed above. For referrring to all the cells in the worksheet you can use the “Cells” while specifing the object.
    9-use-cells-while-specifing-the-object

Here’s the full code that you have just written.

Sub MyMacro()

Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
    With Cells  
        .Font.Size = 16
        .Font.Name = "Verdena"       
    End With   
Next ws

End Sub

With Statement in Excel VBA

A With statement is used in VBA to access all the properties and methods of a mentioned object. Therefore, we need to supply which VBA objectThe “Object Required” error, also known as Error 424, is a VBA run-time error that occurs when you provide an invalid object, i.e., one that is not available in VBA’s object hierarchy.read more we are referring to first, close the With statement with End With, then inside this statement. Then, we can perform all the property changes and methods of the mentioned object.

Table of contents
  • With Statement in Excel VBA
    • How to Use With Statement in Excel VBA?
      • Example #1
      • Example #2
      • Example #3
    • Things to Remember
    • Recommended Articles

Below is the syntax of With Statement in VBA.

With [OBJECT]

     [Code… What needs to be done?]

End With

The object is nothing but a range of cells or cells we are referring to, and then we can change the properties and perform all the methods associated with that specific cell or cell.

How to Use With Statement in Excel VBA?

Below are some examples of using With statements in Excel VBA.

You can download this VBA With Excel Template here – VBA With Excel Template

Example #1

Assume you have a certain value in the A1 cell. We have entered the text as “Excel VBA” in cell A1.

Excel VBA With Statement Example 1.1

Now, we need to do some tasks for this cell, i.e., formatting in excelFormatting is a useful feature in Excel that allows you to change the appearance of the data in a worksheet. Formatting can be done in a variety of ways. For example, we can use the styles and format tab on the home tab to change the font of a cell or a table.read more.

We want to change the font size, name, and interior color, insert a border, etc. Typically, we refer to the cell using VBA RANGE objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.

Code:

Sub With_Example1()

    Range ("A1")

End Sub

Excel VBA With Statement Example 1.2

Now, we access this cell’s “font” property to change the font size.

Excel VBA With Statement Example 1.3

Under the FONT property, we access the Size property and enter size by putting an equal sign.

Code:

Sub With_Example1()

    Range("A1").Font.Size = 15

End Sub

Excel VBA With Statement Example 1.4

Now similarly, we do other formatting tasks, as shown below.

Code:

Sub With_Example1()

    Range("A1").Font.Size = 15
    Range("A1").Font.Name = "Verdana"
    Range("A1").Interior.Color = vbYellow
    Range("A1").Borders.LineStyle = xlContinuous

End Sub

Excel VBA With Statement Example 1.5

It will do all the mentioned tasks, but if you look at the code to perform every formatting activity. We have supplied the cell address every time. It makes the code look lengthy and time-consuming.

Now, we will use VBA With a statement to reduce the entry of cell addresses every time. Open WITH statement in Excel VBA and supply cell address.

Code:

Sub With_Example1()

    With Range("A1")

End Sub

Excel VBA With Statement Example 1.6

Inside the With statement, put a dot to see all the properties and methods of cell A1.

Excel VBA With Statement Example 1.7

The first formatting activity is changing font size, so access FONT. Under this, access the SIZE property.

Code:

Sub With_Example1()

    With Range("A1")
         .Font.Size = 15

End Sub

Example 1.8

Similarly, supply other formatting codes and close VBA With statement.

Code:

Sub With_Example1()

    With Range("A1")
         .Font.Size = 15
         .Font.Name = "Verdana"
         .Interior.Color = vbYellow
         .Borders.LineStyle = xlContinuous
    End With

End Sub

Example 1.9

Run the code to see all the formatting in the mentioned object, i.e., cell A1.

VBA With Example1 - Output

So, all the formatting applies to the cell. Look how cool this technique is.

Example #2

If you want to change all the properties related to the font, you can mention the cell and FONT property.

Code:

Sub With_Example2()

    With Range("A1").Font

    End With

End Sub

Example 2.1

Inside the VBA With Statement, we can see the IntelliSense list. It will show properties and methods related to FONT property only.

Example 2.2

We can perform any set of activities with this now.

Code:

Sub With_Example2()

    With Range("A1").Font
         .Bold = True 'Font will be Bold
         .Color = vbAlias 'Font color will be Alias
         .Italic = True 'Font will be italic style
         .Size = 20 ' Font size will be 20
         .Underline = True 'Font will be underlined
    End With

End Sub

Example 2.3

It will show the result of this below.

VBA With Example 2- Output

Example #3

The below code will access only cell border-related properties.

Code:

Sub With_Example3()

    With Range("B2").Borders
         .Color = vbRed 'Border color will be red
         .LineStyle = xlContinuous 'Full border
         .Weight = xlThick 'Thick border
    End With

End Sub

Example 3.1

The result of this code is as follows.

VBA With Example 3 - Output

Things to Remember

  • A With statement is used to minimize the code.
  • We need to supply the object first for the With statement.
  • Once we supply the specific object, we can access only that object’s properties and methods.

Recommended Articles

This article has been a guide to VBA With. Here, we discuss how to use With…End With Statement in Excel VBA along with examples and downloadable Excel sheet. You can learn more about VBA from the following articles: –

  • VBA Delete Sheet
  • VBA If Else
  • VBA Type Statement
  • Named Range in VBA
 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

При выводе на лист данных из формы (контролов много):  

  With Worksheets(«лист»)  
  .[C5].Value = Me.cboxP.Text
……………..  
End With  

  Понадобилось обратиться к процедуре при выполнении кода из другой формы. Выношу макрос в общий модуль:  

  With Worksheets(«лист»)  
  .[C5].Value = ufrmA.cboxP.Text
……………..  
End With  

  Но их же много, строчек этих, и в каждой ссылка на форму ufrmA… Вот бы:  

  With Worksheets(«лист»)  
With ufrmA  
  .[C5].Value = .cboxP.Text
……………..  
End With  
End With  

  Была надежда, что  различит «листовое» и «форменное». Но нет, не хочет.  

  Можно ли?

 

ikki

Пользователь

Сообщений: 9709
Регистрация: 22.12.2012

You can nest With statements by placing one With block within another. However, because members of outer With blocks are masked within the inner With blocks, you must provide a fully qualified object reference in an inner With block to any member of an object in an outer With block.  

  с буржуинским у меня плоховато, но я понял так:  
вложить-то оно, кшн, можно, но, в данном случае, придётся уточнять для внешнего With:  

  With Worksheets(«лист»)  
With ufrmA  
Worksheets(«лист»).[C5].Value = .cboxP.Text ‘ здесь обязательно
……………..  
End With  
.[c5].value = … ‘ а здесь нет
End With

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

Не-е-е…  
Спасибочки, но хотелось (и не прошло) все внутри и без уточнения :)  
Одно дело, если ссылки на лист1 и лист2. Но здесь же форма. Ведь нам-то ясно, что C5 ну не может быть на форме.  

  Подозреваю, что никак… Обидно, понимаешь :)

 

Да что же за скупость такая: экономить на ссылках ? :-)  

  Dim Sh As Worksheet  
‘………………….  
Set Sh = Sheets(«лист»)  
With ufrmA  
   Sh.[C5].Value = .cboxP.Text
   ‘…………………….  
End With

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

Жадный я. И Уокенбах тоже жадный :)  
«Переменная объекта — это переменная, представляющая целый объект, например, диапа-  
зон или рабочий лист. Переменные объектов имеют особое значение по двум причинам:  
— значительно упрощают программу;  
— ускоряют выполнение программы.»  

  С.М., спасибо, понял ошибку, которая вынудила создать тему: я не так задавал тип переменной (As Range).  
Можно закрываться, а то еще кто пожаднее зайдет, сократит по самое «никуда» :)

 

nerv

Пользователь

Сообщений: 3071
Регистрация: 22.12.2012

>Была надежда, что различит «листовое» и «форменное». Но нет, не хочет.  
>Можно ли?  
Нет. With, насколько я понимаю, временно изменяет цепочку областей видимости. Вы предлагаете компилятору угадать?  

  [С.М.]
>Да что же за скупость такая: экономить на ссылках ? :-)  
товарищ дело говорит )

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#7

12.03.2012 11:10:12

nerv, а как же предложение (в теме о книге) о «правильности» кода? :) Сокращение (в разумных пределах) делает код лучше читаемым. Присвоение объекту переменной избавляет Еxcel от постоянного обращения к объекту.  
Чем плохо?  

  Отвечать не нужно, вопрос «в пустоту». У каждого свои представления о порядке в коде. У меня пока такие :)  

  Хотел создать тему по этому поводу, но вовремя подсказали ссылку на статью «Стиль оформления кода на vb»:  

http://bit.pirit.info/forum/viewtopic.php?t=2793

Понравилась статья? Поделить с друзьями:
  • Excel vba table this row
  • Excel vba with worksheets range
  • Excel vba table filtering
  • Excel vba with worksheet range
  • Excel vba sumifs with or