The With...End With statement allows simplifying access to the properties and methods of a single object so that the object name does not need to be repeated in every expression. All references within the block refer to the specified object.
Example usage:
With myCustomer .Name = "Ivanov" .Balance += 1000 .LastPurchase = Now End With
Benefits:
Question: Can one With block be nested inside another? What happens with property and method references inside the nested block?
Answer: Yes, nesting is possible. However, inside the inner block, dot notation (.) will be interpreted relative to the inner object. If the same property name is used, ambiguity arises.
With obj1 .Value = 10 With obj2 .Value = 20 ' This is obj2.Value, not obj1.Value End With End With
History
In a nested With section, properties with the same name in different objects were used, and the developer expected that the assignment would affect the outer object. As a result, data was written incorrectly, and the issue manifested only when generating a complex report, when the values got mixed up.
History
During code refactoring, the End With blocks were mismatched. In a large code block, this led to expressions referencing another (already closed) instance of the object instead of the expected one, resulting in runtime errors and elusive bugs.
History
In business logic, With was used for nested collections. After updating the class structure, a new property was added with a name that matched the properties of the inner object, causing a conflict and a compilation error, unnoticed due to the lack of unit tests for these cases.