automatically execute an Excel macro on a cell change

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

问题:

How can I automatically execute an Excel macro each time a value in a particular cell changes?

Right now, my working code is:

Private Sub Worksheet_Change(ByVal Target As Range)     If Not Intersect(Target, Range("H5")) Is Nothing Then Macro End Sub

where "H5" is the particular cell being monitored and Macro is the name of the macro.

Is there a better way?

回答1:

Your code looks pretty good.

Be careful, however, for your call to Range("H5") is a shortcut command to Application.Range("H5"), which is equivalent to Application.ActiveSheet.Range("H5"). This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.

With this in mind, I would utilize Target.Worksheet.Range("H5"):

Private Sub Worksheet_Change(ByVal Target As Range)     If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro End Sub

Or you can use Me.Range("H5"), if the event handler is on the code page for the worksheet in question (it usually is):

Private Sub Worksheet_Change(ByVal Target As Range)     If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro End Sub

Hope this helps...



回答2:

Handle the Worksheet_Change event or the Workbook_SheetChange event.

The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.



回答3:

I prefer this way, not using a cell but a range

    Dim cell_to_test As Range, cells_changed As Range      Set cells_changed = Target(1, 1)     Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )      If Not Intersect(cells_changed, cell_to_test) Is Nothing Then         Macro     End If


回答4:

I have a cell which is linked to online stock database and updated frequently. I want to trigger a macro whenever the cell value is updated.

I believe this is similar to cell value change by a program or any external data update but above examples somehow do not work for me. I think the problem is because excel internal events are not triggered, but thats my guess.

I did the following,

Private Sub Worksheet_Change(ByVal Target As Range)    If Not Intersect(Target, Target.Worksheets("Symbols").Range("$C$3")) Is Nothing Then    'Run Macro End Sub


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