×

Excel VBA : With End-with Constructs

With End-with Constructs

The With-End With construct enables the user to perform multiple operations on a single object. If you are going to perform several different actions on the same object and typing the same object over and over, use the With ....... End With. After an object is assigned to a variable, VBA can access it more quickly than it can a lengthy reference that has to be resolved.

For example, if you want to change multiple properties on a single object, place the property assignment statements inside the With...End With block, wherein the objectExpression will refer to the object only once instead of once for each property assignment.

Benefits of With End-with Constructs

If in your code, you need to access the same object in multiple statements, you can advance the following advantages by using the With end statement:

  • You don't need to assess a complicated expression or object numerous times or assign the result to a temporary variable to refer to its members various times.
  • You make your code more readable by eliminating repetitive qualifying expressions.
  • You can improve the speed of the code and can faster the processing time.

Syntax

With objectExpression
    Statement1
    Statement2
    ….
    StaementN
 End With 

Parameter With End-with Constructs

objectExpression (Required) – This parameter represents an expression that evaluates to an object. The expression is evaluated only once and can be arbitrarily complex. The expression can assess to any data type, including primary types.

statements (Optional) – This parameter represents one or more statements coded between With and End With that may refer to members of an object that's produced by the evaluation of objectExpression object.

End With (required) - Terminates the definition of the With block.

Nested With End

Nested With...End With statements may be a bit confusing if the objects that are being referred to aren't clear from the point of context. The programmer must provide a fully qualified reference to an object that's in an outer With block when the object is referenced from within an inner With block.

Example 1: Write a macro demonstrating the need of with end constructs.

Sub Without_with_End_option()
 'putting string value in the active cell
 ActiveCell.Value = "VBA is easy to learn."
 'enabling the text to be bold
 ActiveCell.Font.Bold = True
 'changing the font color to red
 ActiveCell.Font.Color = vbRed
 'changing the font
 ActiveCell.Font.Name = "Algerian"
 'altering the font size to 22
 ActiveCell.Font.Size = 22
 'enabling the Italic option for the activecell.
 ActiveCell.Font.Italic = True
 End Sub 

Output

macro demonstrating the need of with end constructs

In the above code, you will notice that we have accessed the ‘ActiveCell’ object in multiple statements which can also be performed on a single object.  

Example 2

Sub With_End_Example()
 'putting string value in the active cell
 ActiveCell.Value = "VBA is easy to learn."
     With ActiveCell.Font
         'enabling the text to be bold
         .Bold = True
         'changing the font color to red
         .Color = vbRed
         'changing the font
         .Name = "Algerian"
         'altering the font size to 22
         .Size = 22
         'enabling the Italic option for the activecell.
         .Italic = True
     End With
 End Sub 

Output

Nested With End

Nested With..End

Example 3

Option Explicit
 Public add As Integer
 Public Name As String
 Public x As Integer
 Public y As Integer
 'Declaring a class
 Sub sum()
 add = x + y
     'with end-with construct
     With ActiveCell
         .Value = "Hello " + Name
             'nested with
             With .Font
                 .Bold = True
                 .Color = vbRed
                 .Name = "Algerian"
             End With
         .Offset(1, 0) = "Sum = "
         .Offset(1, 1).Value = add
     End With
 End Sub 
 'Declaring a module
 Sub Math()
 Dim obj As New Class1
 Dim IB As String
 Dim MB As String
 'Declaring input box
 IB = InputBox("Enter your name")
 'Declaring message box
 MB = MsgBox("Do you want to add the numbers!", vbYesNo)
 'If user selects yes option
 If MB = vbYes Then
     'With End-with Constructs
     With obj 
         .Name = IB
         .x = 5
         .y = 6
         .sum
     End With
 End If
 'If user selects No option, program will terminate
 If MB = vbNo Then Exit Sub
 End Sub 

Output

Press F5 to run the VBA code. A prompt box will pop up. Type your name and click on OK.

Msgbox will pop up. If you want to add the number click on YES else on NO button. We have clicked on YES in the following code.

Msgbox will pop up

You will notice in the excel sheet in the active cell the changes have occurred (as shown below).

Hello Rahul

Related Topics

Excel VBA Str Function

VBA Str Function: The Str function in VBA converts the given number into a string representation of that number. Syntax Str (Number) Parameter Number (required) – This parameter represents the numeric value that you want...

1 minute read.

Excel VBA IsDate Function

VBA IsDate Function: The IsDate function in VBA returns a Boolean value indicating whether the given expression is interpreted as a VBA Date or not. Syntax IsDate (Expression) Parameter Expression (required) – This parameter...

1 minute read.

Excel VBA IsError Function

VBA IsError Function: The IsError function in VBA returns a Boolean value showing whether the specified Expression represents an error or not. Syntax IsError (Expression) Parameter Expression (required)- This parameter represents the variant that you...

1 minute read.

VBA Screen Updating

What is VBA Screen Updating property? Screen Updating is a VBA property which is used to display the output generation while running the code. If this property is enabled, we could see...

6 minutes read.

Excel VBA Now Function

Excel VBA Now Function: The Now function in VBA returns the current date and time.  Syntax Now () Parameter NA Return This function returns the current date and time.  Example 1 Sub NowFunction_Example1() 'It will return...

1 minute read.

Excel VBA AutoFilter

One of the reasons for Excel VBA’s popularity is its capability to filter and analyze data from huge database with the help of a method known as AutoFilter. This method permits a...

4 minutes read.

Excel VBA Tan Function

VBA Tan Function: The Tan function in VBA returns the tangent for the specified angle in radians. Syntax Tan (Number) Parameter Number (required) – This parameter represents the angle supplied in radiant that you want...

1 minute read.

Steps to Create a Pivot Table

Steps to Create a Pivot Table: Pivot Tables can be easily automated through VBA coding. To create a Pivot Table in VBA, follow the below step by step procedure to...

4 minutes read.

Excel VBA Time Function

Excel VBA Time Function: The Time function in VBA returns the current time. Syntax Time () Parameter NA Return This function returns the current time.  Example 1 Sub TimeFunction_Example1() ' returns the current time Dim time_val...

1 minute read.

Excel VBA Right Function

VBA Right Function: The Right function in VBA returns a substring from the end of the given string. Syntax Right (Str, Length) Parameter Str (required) – This parameter represents the string from which you want to...

1 minute read.

Excel VBA Day Function

The function Day in VBA returns the day number (from 1 to 31) for the given date value. Syntax Day (Date) Parameter Date (required) – This parameter represents the date. Return This function returns the day...

1 minute read.

VBA VBScript Regex Methods Regex

VBA VBScript Regex Methods Regex The VBA Regex supports 3 methods which are as follows: ExecuteReplaceText Execute The execute method is used to extract a match from the given based on the defined matching...

3 minutes read.

Finding Last Row or Column in Excel VBA

Finding Last Row or Column in VBA Finding the last used row, column, or cell is one very commonly used task when we write macros and VBA applications.  Like other codes...

5 minutes read.

Excel VBA LCase Function

VBA LCase Function: The LCase function in VBA converts the given String into lower case text. Syntax LCase (String) Parameter String (required)- This parameter represents the text string that you want to convert to...

1 minute read.

Excel VBA MessageBox

Message Box The MsgBox in Excel VBA is a dialog box used to inform the users of your program by showing a custom message or get some necessary inputs such as Yes/No or...

4 minutes read.

Excel VBA DateValue Function

The DateValue function in VBA returns a VBA Date from the given String representation of a date wherein the time information is ignored. It is unable to interpret dates that include the...

1 minute read.

Excel VBA LTrim Function

VBA LTrim Function: The LTrim function in VBA removes the leading spaces from a supplied text string. Syntax LTrim (String) Parameter String (required) - This parameter represents he text string that you want to remove...

1 minute read.

Introduction to Visual Basic Editor Window

How to enable the Developer Ribbon Tab? In order to work with VBA, users need to make a small change in Excel to display a new tab (Developer) at the top of the...

5 minutes read.

Excel VBA: DO WHILE….Loop

DO WHILE….Loop The “Do While” Loop is the same, unlike the FOR statement, just that it will keep on looping till the specified condition is true. It is used when we want to...

3 minutes read.

Excel VBA: IF THEN Statement

VBA Excel: IF THEN StatementThis conditional statement enables you to check one condition and on the basis of that then run one or multiple statements if the condition holds. If...

1 minute read.