Monday, June 20, 2005

 

Rule 9: Select is evil

The macro recorder likes producing this sort of code.


Range("E13:G16").Select
Selection.Font.Bold = True


This is evil.

Here is why.

Bundle the code up in a subroutine


Public Sub Highlight()
Range("E13:G16").Select
Selection.Font.Bold = True
End Sub


Seems reasonable.

However lets say we have another subroutine


Public Sub FormatCells()
Range ("A14:B20").Select
Highlight()
With Selection.Interior
.ColorIndex = 7
.Pattern = xlSolid
End With
End Sub


The idea is that we want to set the colour of the sells A14:B20, and highlight E13:G16.

Sorry, it doesn't work. You cannot nest the calls, because of the .Select statement. It changes the selection and is a side effect of the call to Highlight. The end result is you cannot decompose your subroutines in this way.

The code should be this


Public Sub Highlight()
Range("E13:G16").Selection.Font.Bold = True
End Sub

Public Sub FormatCells()
Highlight()
With Range ("A14:B20").Interior
.ColorIndex = 7
.Pattern = xlSolid
End With
End Sub


This is now side effect free.

ie. Remove all the .select / .selection from the code.
Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]