Search code examples
vbalanguage-featureslanguage-comparisons

VBA With statement equivalent in other languages


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?


Solution

  • There's a useful Wikipedia article that describes this as method cascading, basically a type of syntactic sugar. The article includes , and as other languages with this feature.

    It's in Javascript as well, but note that:

    ...using with is not recommended, and is forbidden in ECMAScript 5 strict mode

    const obj = {a: 1, b: 2}
    
    with (obj) {
      const k = a + b; // no need for a .
      console.log(k)
    }

    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.:

    k = 99
    With foo
        With .bar
            With .baz
                If Not .qux Is Nothing Then
                    k = 4
                End If
            End With
            For i = 1 to .NumberOfThings
                k = k + i
            Next i
        End With
        .DoAllTheThings(k, SomeOtherVariable)
    End With
    

    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.