With...End With Statements
Executes a series of statements making repeated reference to a single object or structure.
With object [ statements ] End With
- Required. Expression. Can evaluate to any data type, including elementary types.
- Optional. One or more statements following With that are executed on object.
- End With
- Terminates execution of the With block.
With...End With allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, to change a number of different properties on a single object, place the property assignment statements within the With...End With, referring to the object once instead of referring to it with each property assignment. The following example illustrates use of With...End With to assign values to several properties of the same object:
With MyLabel .Height = 2000 .Width = 2000 .Text = "This is MyLabel" End With
Note Once you have entered a With...End With, you cannot reassign object until you have passed the End With. 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.
You can nest With...End With statements by placing one within another. However, because members of outer statements are masked inside the inner statements, you must provide a fully qualified object reference in an inner With...End With to any member of an object in an outer statement.
You cannot use GoTo to branch from outside a With...End With to a label inside it. If you with to exit before all the statements have been executed, put a label on the End With statement and branch to that.
This example uses the With statement to execute a series of statements on a single object. The object
MyObject and its properties are generic names used for illustration purposes only.
With MyObject .Height = 100 ' Same as MyObject.Height = 100. .Text = "Hello World" ' Same as MyObject.Text = "Hello World". .ForeColor = Color.Green ' Same as MyObject.ForeColor = Color.Green. .Font = New Font(.Font, FontStyle.Bold) ' Same as: ' MyObject.Font = New Font(MyObject.Font, FontStyle.Bold). End With