|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
With...End With Statement (Visual Basic)
Executes a series of statements making repeated reference to a single object or structure.
With...End With allows you to perform a series of statements on a specified object without requalifying the name of the object. If the qualification path to the object is long, using With...End With can improve your performance. A With block also reduces repetitive typing of the qualification path and the risk of mistyping one of its elements.
For example, to change a number of different properties on a single object, place the property assignment statements inside the With...End With, referring to the object only once instead of for each property assignment.
Data Types. The data type of object can be any class or structure type, or even a Visual Basic elementary type such as Integer. The .NET Framework supports all elementary types with classes or structures, which have members you can access inside a With block.
Declaration. You must declare object before you enter the With block. You cannot declare it in the With statement.
Number of Iterations. A With block is not an iterative construction. Unless there is a loop inside the block, the statements run only once.
Nesting Structures. You can nest With...End With structures by placing one structure within another. For an example, see.
However, because members of outer statements are masked inside the inner statements, you must provide a fully qualified object reference in an inner With block to any member of an object in an outer With block.
You can also nest different kinds of control structures within one another. For more information, see.
Transferring Out of the Structure. Visual Basic does not support theto transfer control out of a With block. If you need to exit before all the statements have been executed, put a label on the End With statement and use the to branch to it. For more information, see .
You cannot transfer control either from outside a With block to inside it, or from inside it to the outside. You can call a procedure from inside the block, but control returns to the following statement.
Accessing Other Objects. Once you have entered a With block, you cannot reassign object until you have passed the End With statement. Therefore, you can access the methods and properties of only the specified object without qualifying them. You can use methods and properties of other objects, but you must qualify them with their object names.
The following example uses a With block to execute a series of statements on a single object. The example assumes that object testObject has already been created and exposes the referenced properties.