First question, so please be gentle. SO has been extremely helpful to me since I started writing and editing code, so I hope to contribute.
I'm trying to streamline (wherever possible) a program that performs a lot of checks repeatedly, line by line (user input is multiline). The question is specifically thus: for a sub that's run repeatedly (called multiple times by another), should I declare its variables 1) globally - even though they may not actually be used - 2) privately in the beginning of the sub in question, or 3) privately once the program determines they're needed by conditions?
1) would be:
Public VBase as Integer, VTop as Integer, VAWX as Boolean
For 2) and 3), the difference is with VBase and VTop, 2) being:
Sub XVolcanicAsh()
Dim VBase as Integer, VTop as Integer, VAWX as Boolean
' <snip all the code>
End Sub
And 3) being:
Sub XVolcanicAsh()
Dim VAWX As Boolean 'this one's always used regardless
For ROW = 5 To NUMLINE + 4
' <snip code involving VAWX>
If Sheets("QA").Cells(ROW, 31).Value = "" Then
' the variables won't be used because the cell's blank
Else
Dim VBase As Integer, VTop As Integer
VBase = Mid(Sheets("QA").Cells(ROW, 31).Value, 3, 3)
VTop = Right(Sheets("QA").Cells(ROW, 31).Value, 3)
' <snip other code>
End If
Next ROW
End Sub
The question is less for this specific instance than as a template for scrubbing the entire program, since there are a lot of global variables currently declared that only get used in a handful of lines - but the subs containing them are typically called multiple times.
The extent of my understanding here is that 1) will keep the variables in memory until the main sub ends, while 2) and 3) will dump them once this sub ends; and also that 3) may dimension them multiple times. (I am still unclear as to the precise consequences of this, but thus far it's not throwing errors at me.)
Is there a significant difference, performance-wise, between 1), 2), and 3)? And which, if any, is best coding practice? Maybe my search skills aren't what they should be, but neither Google nor SO's internal search has afforded me a proper answer.
2)because of locality