1

I realized that VBA Editor (Excel 2019 VBE) change case of variables when you have different variables (different scope) but same name with different case. For example, we have the code below, which have 3 "variables" Var1, Var2 and Var3, and it works fine:

Const Var1 As Long = 1
Dim Var2 As Long

Public Property Get Var3() As Long
    Var3 = 3
End Property

Sub Test_A()
    Debug.Print Var1, Var2, Var3 'prints 1 0 3
End Sub

IF we add a second subroutine Test_B, and inside it we declare 3 variables with same name but different case, var1, var2 and var3, the code still works just fine, but all 6 variables (3 module level and 3 subroutine level) change case to be in the same case as the last one declared (so module-level Var1 change to var1 because I've just declared a subroutine-level var1).

Const var1 As Long = 1
Dim var2 As Long

Public Property Get var3() As Long
    var3 = 3
End Property

Sub Test_A()
    Debug.Print var1, var2, var3 '1 0 3
End Sub

Sub Test_B()
    Dim var1 As Long, var2 As Long, var3 As Long
    var1 = 10: var2 = 20: var3 = 30
    Debug.Print var1, var2, var3 'prints 10 20 30
End Sub

Should that behaviour trying to say something? Is it some real issue to be concerned with? Or is it just fine?

sergio trajano
  • 189
  • 1
  • 1
  • 14
  • 4
    1. Variables in VBA **are not case sensitive**! After using them, VBA show them **as they have been declared**. 2. When you try using the same string variable, but changing some letters (UCase, LCase), VBA only try suggesting, remembering what you used before. 3. If you declare a global variable (on top of the module) you should only give values to it (as it is). But if you locally (in a procedure) declare a similar one in terms of used string, VBA **uses the local declared one**. No connection between the former variable case and the new one... – FaneDuru Dec 13 '22 at 11:43
  • 2
    It is good to have `Option Explicit` on top of each module! In this way it oblige you to declare all variable, fact which will solve many variables string spelling mistakes. For instance, using `MyVar0` against `MyVaro`, or `Var1` atainst `Varl`... – FaneDuru Dec 13 '22 at 11:46
  • Thanks, @FaneDuru! If you add the comment as an answer, I will accept it. I will change the title to something less misleading as well. – sergio trajano Dec 13 '22 at 11:50
  • 1
    Not enough supplied information to place an answer, I think... I only tried clarifying the issue in discussion and I am glad you understood the way in which VBA treats the variables from case sensitive point of view. – FaneDuru Dec 13 '22 at 12:17

0 Answers0