Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

excel VBA run macro automatically whenever a cell is changed

Tags:

Is there a simple way to get Excel to automatically execute a macro whenever a cell is changed?

The cell in question would be in Worksheet("BigBoard").Range("D2")

What I thought would be a simple Google inquiry is proving to be more complicated - every sample involved intersects (whatever those are) or color formatting or any other number of things that appear to be irrelevant.

like image 647
kamelkid2 Avatar asked Mar 11 '13 11:03

kamelkid2


People also ask

How do I automatically run a macro when a cell value changes?

Go to the VBA Editor (Alt + F11) and double-click the name of the spreadsheet that contains the cell that will change or just right-click the worksheet tab and click View Code. In the window that opens, select Worksheet from the left drop-down menu and Change from the right drop-down menu.

Can a macro run automatically without opening Excel?

You can't run a Excel VBA Macro without opening the File that contains the macro. If you want you can launch the excel application in hidden mode and then run the macro after opening the file in hidden mode from a VBS file.


2 Answers

Yes, this is possible by using worksheet events:

In the Visual Basic Editor open the worksheet you're interested in (i.e. "BigBoard") by double clicking on the name of the worksheet in the tree at the top left. Place the following code in the module:

Private Sub Worksheet_Change(ByVal Target As Range)     If Intersect(Target, Me.Range("D2")) Is Nothing Then Exit Sub         Application.EnableEvents = False 'to prevent endless loop         On Error Goto Finalize 'to re-enable the events               MsgBox "You changed THE CELL!"     End If Finalize:             Application.EnableEvents = True End Sub 
like image 82
Peter Albert Avatar answered Jan 03 '23 11:01

Peter Albert


Another option is

Private Sub Worksheet_Change(ByVal Target As Range)     IF Target.Address = "$D$2" Then         MsgBox("Cell D2 Has Changed.")     End If End Sub 

I believe this uses fewer resources than Intersect, which will be helpful if your worksheet changes a lot.

like image 35
user2140261 Avatar answered Jan 03 '23 12:01

user2140261