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.
- 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
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.
count_wsasworksheets_countor justcount. I feel that a variable's name should read easily and clearly.worksheets_countmakes it clearer. I struggle sometimes with the naming and am not sure if I'm opting for the best choice. I shouldn't shy away from longer variable names if they make the code more readable, right? I have looked up naming conventions and the different ways to go about it, but when writing code, there are always cases where I end up with a dodgy name.