Various problems in Excel VBA involving selections (and how to avoid them) and "heavy" loops have been discussed on this forum earlier on. I'd like to expand on that a little. Let's say I want to change a certain string to another string and do something else with numeric data. Consider the following code:
Option Explicit
Sub LoopExample()
Dim rownumber, colnumber As Integer
' Step 1: start a loop from a desired position
For rownumber = 30 To 3000
For colnumber = 30 To 3000
' Step 2: check that the cell is not empty
If IsEmpty(Cells(rownumber, colnumber).Value) = False Then
' Step 3: change all "Cat" texts to "Dog"
If Cells(rownumber, colnumber).Value = "Cat" Then
Cells(rownumber, colnumber).Value = "Dog"
' Step 4: if the cell value is numeric...
ElseIf IsNumeric(Cells(rownumber, colnumber).Value) Then
' ...check another thing and execute something accordingly
If (Cells(rownumber, colnumber).Value) / 2 < 0.5 Then
Cells(rownumber, colnumber) = Round(Cells(rownumber, colnumber).Value, 4)
Else
Cells(rownumber, colnumber) = Round(Cells(rownumber, colnumber).Value, 1)
End If
End If
End If
Next colnumber
Next rownumber
End Sub
Now, this code works "perfectly" but is hardly an efficient one. Should I optimize it by: 1) first finding all cells that contain data in the first place, 2) loop only over those cells again, 3) divide the data now even further to numeric and non-numeric data, and 4) execute what I want on these numeric and non-numeric ranges? Or should I possibly combine some of these steps in one loop?