(Solved) – VBA: Using the same variable name in different subs

(solved)-–-vba:-using-the-same-variable-name-in-different-subs

I have a question about naming conventions and using the same variable name in different subs. It’s been bugging me since I started with VBA.

  1. Is it good practice to use the same variable name in different modules? The subs don’t interact with each other. For example, I cycle through the sheets in my workbook in two different modules and so far have used the same name for the counter variable (count_ws):

Module 1:

Sub Test()
    Dim count_ws As Long
    
    For count_ws = 2 To ThisWorkbook.Worksheets.Count
        Debug.Print "Module1"
    Next count_ws
End Sub

Module 2:

Sub Test2()
    Dim count_ws As Long
    
    For count_ws = 2 To ThisWorkbook.Worksheets.Count
        Debug.Print "Module2"
    Next count_ws
End Sub

If this is not ok, what’s the best alternative? The reason I repeat the name is that I didn’t want to make the variable name too long, like count_ws_module1 and count_ws_module2

  1. Passing a variable into another sub: Same question, is it advisable to keep the same name? I feel like it could be confusing if I call the variable one name in the first sub, and then something else in the other sub.

    Sub Test3()
    Dim wsLoans As Worksheet
    Dim wsBS As Worksheet

         Set wsLoans = ThisWorkbook.Sheets(2)
         Set wsBS = ThisWorkbook.Sheets(3)
    
         Call Test4(wsLoans)
     End Sub
    
     Sub Test4(ByVal wsLoans As Worksheet)
         wsLoans.Range("A1").Value = "Module 4"
     End Sub
    

So, for me this approach seems the most readable and avoids confusion, but I’m happy to hear other opinions. In Sub Test4 I could simply name the Sheet ws. Or wsLoans_Test4, but does this actually help?

I just want to make sure I get this right and build good habits.

Leave a Reply

Your email address will not be published. Required fields are marked *