In VBA there is a cool feature called a With
statement that kind of lets you set the global scope for a block of code. This is useful to change multiple fields of an object and to call methods.
Here is an example:
With Forms!main
.Filter = "tel IS NOT NULL"
.FilterOn = True
.Requery 'This is a method!
If .Recordset.RecordCount> 3 Then
.BackColor = "Red"
End If
End With
In this example all the statements that begin with .
refer to fields and methods of Forms!main
.
I haven't come across a feature like this in any modern language (Javascript, c#, python) and I am wondering if there is a reason for this?
There's a useful Wikipedia article that describes this as method cascading, basically a type of syntactic sugar. The article includes dart, pascal and smalltalk as other languages with this feature.
It's in Javascript as well, but note that:
And it's also included in C# 9.0 according to this answer - read all the answers for context.
The other interesting post is this one which has some of the flavour for my answer to the question of 'why' this feature is not more widespread.
The 'sugar' can get 'too sweet' e.g.:
Suddenly use of
With
is not as useful compared to your more terse and readable example. We can see the feature generates controversy (due to over-use) and this is why it has not really made it into the mainstream.