Hi Everyone!
Writting a For loop in vba is not a big deal but one common mistake which lot of developers tend to do. They tend to write the for as below:
InEfficient Method:
Sub prTest()
'Error Handler
On Error GoTo Err_PrTest:
Dim intStartCounter As Integer
Dim intLoopCounter As Integer
Dim rngTest As Range
intLoopCounter = 5
Set rngTest = Range("Test")
For intStartCounter = 1 To intLoopCounter
If rngTest(intStartCounter, 1) = "Test" Then
'Do Nothing
End If
Next intStartCounter
Exit_PrTest:
Exit Sub
Err_PrTest:
GoTo Exit_PrTest
End Sub
2)Efficient Method
Sub prTest()
'Error Handler
On Error GoTo Err_PrTest:
Dim intStartCounter As Integer
Dim intLoopCounter As Integer
Dim rngTest As Range
intLoopCounter = 5
Set rngTest = Range("Test")
For intStartCounter = 1 To intLoopCounter
If rngTest(intStartCounter, 1) = "Test" Then
'Exit the for loop as soon as you find the Test. Other as soon as the purpose of for loop
'is satisfied exit
Exit For
End If
Next intStartCounter
Exit_PrTest:
Exit Sub
Err_PrTest:
GoTo Exit_PrTest
End Sub
The difference between 1 & 2 is that in case of 2 you exit the for loop once the purpose of FOR loop is satisfied and therefore you save execution time. 2 will make code more optimized.
Cheers!
This blog is about Technology. One ultimate destination for tutorials on programming languages, exploring about complex situations in different programming languages. Also Knowing about most wanted technologies now and in Future. The Major content as of now will be focussed on Excel and Visual Basic for Applications(VBA). Have a happy reading...!!
Friday, December 25, 2009
Subscribe to:
Post Comments (Atom)
Followers
Blog Archive
About Me
- Ravindra Singh Yadav
- Hello World!. I am an aspiring blogger, striving towards knowing more about various Technologies and innovating about it. I am full of Energy, Enthusiasm to learn more and more....
No comments:
Post a Comment