Automatic macro like tip006 but for a single Cell Reference


Posted by Steve on February 28, 2001 2:34 AM

anyone know how to change the code in Tip006 so that your functions will only run when a cell has been changed.

Several readers have asked questions which require Excel to run a section of macro every time a value changes.

First, the improved method available only in XL97: Excel 97 has some new event handlers that allow a macro to be run every time a cell changes.

Let's say that anytime a value greater than 100 is entered in column A, you want to format the cell next to it to be red.


Open the Visual Basic Edit (Tools>Macro>Visual Basic Editor)
In the left window, right click Sheet1 and select View Code.
At the top of the Book1 - Sheet1 Code dialog box, there are two dropdowns. From the left dropdown select Worksheet. From the right dropdown, select Change.
Enter the following lines of code:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.Column = 1 Then
ThisRow = Target.Row
If Target.Value > 100 Then
Range("B" & ThisRow).Interior.ColorIndex = 3
Else
Range("B" & ThisRow).Interior.ColorIndex = xlColorIndexNone
End If
End If
End Sub

Any time a value in a cell is changed, this macro will be run. The variable Target will tell you which cell and the new value of the cell. Surprisingly, using this method does not significantly slow down the process.



Posted by David Hawley on February 28, 2001 2:48 AM


Hi Steve

Just a couple of other pointers.

To open a sheet module quickly, right click on the sheet name tab and select "View Code"

When using a sheet change event I always use:

If Target.Cells.Count > 1 Then Exit Sub

as the first line. This will prevent any Run time errors caused by the user changing more than one cell at a time, such as a entering an entry in an array of cells or Copying in more than one cell.


Dave


OzGrid Business Applications