Automatically running macros in a sheet
If you create a private macro called Worksheet_Change
within a
particular worksheet then it will be run everytime something changes in that
sheet. Within the body of the macro you can define a range of cells, and then
only execute code if one of those cells has been changed. The brief example
below shows the concept:
Private Sub Worksheet_Change(ByVal Target As Range) ' Define a Range variable and set it to the cells that you want to watch. ' Here, it is cells A1 and B1. Dim keyCells As Range Set keyCells = Range("a1:b1") ' If one of the cells in keyCells has changed, then run the code within ' the if statement. If Not Application.Intersect(keyCells, Range(Target.Address)) Is Nothing Then ' Check to make sure that the values in A1 and B1 are greater than 1 ' (if they are set to 1, 1 or 1, 2 then our original values will be ' overwritten. If either are zero then an error would occur when ' the Cells function was used within the If statement. If Range("b1").Value > 1 And Range("a1").Value > 1 Then ' Select the cell defined by the values in A1 and B1, change it's ' background colour, and set it to contain "HelloWorld". Cells(Range("b1"), Range("a1")).Select With Selection.Interior .ThemeColor = xlThemeColorAccent1 End With ActiveCell.FormulaR1C1 = "HelloWorld" End If End If End Sub