Why it is important to define variables with Dim in Excel VBA

During a seminar a participant showed two macros in Excel: one which had no definitions of the data types of the variables used in the macro and another where the data types of the variables was clearly defined using the keyword ‘dim’. On the face of it both the macros appeared to deliver same results. A closer look, however, showed that the macro where the variable data types were not defined clearly ran much slower. Now the difference in time required for the calculations was quite large even in this simple example. What if the macro had more variables and was required to perform much higher numbers of computations? Therefore it became evident that it is important to define variables with ‘dim’ in Excel VBA. Watch the VBA training video before you study the code which employs the ‘Timer’ function to nail the problem:

 

You may like to watch the video on YouTube.

The complete VBA code of Module 1:

Sub calculateTime()
startTime = Timer
x = 0
y = 0
For i = 1 To 5000
x = x + 2
y = x + 2
For j = 1 To 5000

P = x – y + i

Q = y + x – i

R = y / x * i

Next j
Next i

endTime = Timer
Range(“A2”) = P
Range(“B2”) = Q
Range(“C2”) = R
‘MsgBox “Total Time taken for calculation ” & (endTime – startTime) & ” seconds.”
MsgBox Format(endTime – startTime, “0.0”)

End Sub

Sub calculateTime2()
Dim startTime As Date, endTime As Date
Dim i As Long, j As Long
Dim x As Single, y As Single, P As Single, Q As Single, R As Single
startTime = Timer
x = 0
y = 0
For i = 1 To 5000
x = x + 2
y = x + 2
For j = 1 To 5000

P = x – y + i

Q = y + x – i

R = y / x * i

Next j
Next i
endTime = Timer
Range(“A3”) = P
Range(“B3”) = Q
Range(“C3”) = R
‘MsgBox “Total Time taken for calculation ” & (endTime – startTime) & ” seconds.”
MsgBox Format(endTime – startTime, “0.0”)

End Sub

The complete macro code of Module 2:

Sub calwithoutDim()
x = 0
y = 0
For i = 1 To 5000
x = x + 2
y = x + 2
For j = 1 To 5000
P = x – y + i

Q = y + x – i

R = y / x * i

Next j
Next i

Range(“A2”) = P
Range(“B2”) = Q
Range(“C2”) = R

End Sub

Sub calwithDim()
Dim startTime As Date, endTime As Date
Dim i As Long, j As Long
Dim x As Single, y As Single, P As Single, Q As Single, R As Single
x = 0
y = 0
For i = 1 To 5000
x = x + 2
y = x + 2
For j = 1 To 5000

P = x – y + i

Q = y + x – i

R = y / x * i

Next j
Next i

Range(“A3”) = P
Range(“B3”) = Q
Range(“C3”) = R
End Sub

Further Reading

Timer Function

 

Leave a Reply

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