When is a Dim statement processed in the compiling of VBA code? Is there any efficiency gain if I do this?:
Dim oFileDiag As FileDialog
Set oFileDiag = Application.FileDialog(msoFileDialogFilePicker)
If oFileDiag.Show = -1 Then
'// Dim statement further down in the code...
Dim ofdSelected As FileDialogSelectedItems
Set ofdSelected = .SelectedItems
End If
As opposed to this?:
'// Dim statement at the beginning of the code...
Dim oFileDiag As FileDialog
Dim ofdSelected As FileDialogSelectedItems
Set oFileDiag = Application.FileDialog(msoFileDialogFilePicker)
If oFileDiag.Show = -1 Then
Set ofdSelected = .SelectedItems
End If
As I understand it (I’ve been wrong before), there is no gain in efficiency in VB(A). Declaring any variable anywhere in the routine will use the same resources (though your variable won’t be available until below its declaration).
The declaration of an object variable (
Dim) only creates the reference, it does not instantiate the object until theSet. However, watch out for the opposite problem in this sort of construct:This seems like it might be convenient, since you don’t have to do an explicit
Set... = New.... But the gotcha is that every time you usersFooat runtime the code has to check whether or not it’s been instantiated. Much better this way:This is, to some extent, a “religious” difference, at least in languages where there isn’t any real difference in overhead. The most common practice in VB(A) is to declare all variables at the beginning of the routine, though there are some who argue that keeping the declaration as close as possible to the first use is “clearer” (not to those of us who are conditioned to expect them all at the beginning, it’s not…).