Search code examples
vbavb6excelprogramming-languages

Chained assignment in VBA


Like C/CPP/CSharp/JScript, how can we do chained assignment in VBA? In other words, does VBA have right-associativity of assignment operator?

For example in C-sharp and JavaScript, we can use:

var alpha, bravo, charlie;
alpha = bravo = charlie = "hello";

Now writing this expression in VBA would have to:

Dim alpha, bravo, charlie
alpha = "hello"
bravo = "hello"
charlie = "hello"

But we can't use:

Dim alpha, bravo, charlie
alpha = bravo = charlie = "hello"

VBA doesn't allow to collapse the expressions. Is there any other way to do that?


Solution

  • No, VBA doesn't have the right-associativity for assignment operator. However, VBA does have the right-associativity or chaining operations for other logical operators. Consider the following expression:

    alpha = 3
    bravo = 5
    charlie = 4
    
    alpha = bravo < charlie
    
    MsgBox(alpha) 'would display false
    
    alpha = 3
    bravo = 5
    charlie = 4
    
    alpha = bravo > charlie < alpha
    
    MsgBox(alpha) 'would display ture .. because (bravo > charlie) is true 
                                          'and true (or 1) less than alpha
    

    However, VBA interpreter prioritize the comparison operator over assignment operator, both are represented by =. To wit,

    alpha = bravo = "hello"
    MsgBox(alpha) 'would display false, because bravo <> "hello"
    

    Thus, you need to use multiple statements explicitly for assignment.