excel VBA run macro automatically whenever a cell is changed

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

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.

回答1:

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!" Finalize:             Application.EnableEvents = True End Sub 


回答2:

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.



回答3:

In an attempt to find a way to make the target cell for the intersect method a name table array, I stumbled across a simple way to run something when ANY cell or set of cells on a particular sheet changes. This code is placed in the worksheet module as well:

Private Sub Worksheet_Change(ByVal Target As Range) If Target.Cells.Count > 0 Then 'mycode here end if end sub 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!