Locked lesson.
About this lesson
How "With" blocks can tighten up your code and ensure your code targets the objects you expect.
Exercise files
Download this lesson’s related exercise files.
With blocks.xlsm26.2 KB With blocks - Completed.xlsm
27.3 KB
Quick reference
With blocks
Understanding how to use and read With blocks in VBA code.
When to use
To simplify your code so it is easier to read and write, as well as more efficient to run.
Instructions
Benefits
- Allows you to shorten code so that the object name only needs to be included once
- Allows you to save on typing as lines can be started with a single period, referring to the With block parent
- Helps code become a tiny bit faster as it doesn't have to navigate the full object model chain
With block structure:
With <object>
.Property1 = x
.Property2 = y
.Property3.Property1A = z
End with
Hints & tips
- Indent all the lines of code in the With statement, to make it clear that they are part of the same With statement
- With statements can be nested inside each other.
…
Login to downloadLesson notes are only available for subscribers.