Cell Value Change Event and Running a Continuous M

2020-07-27 02:22发布

问题:

I want my macro to run automatically when Sheet1 is open AND a value is changed in any of the drop down menus in Column B. I assume I can write a couple of event listener wrappers such as:

' pseudocode    
While Sheet1 is open
        When a dropdown value is changed in column B
            Call Update
        End When
End While

I've found a few links online, but I don't quite understand. In these links, they have code referring to Target. Is Target a named range? I haven't had any luck implementing these. I'm thinking these links could have an answer to my problem.
http://www.mrexcel.com/forum/excel-questions/95341-running-macro-continuously.html
http://msdn.microsoft.com/en-us/library/office/ff839775(v=office.15).aspx

Thanks

回答1:

You can use a worksheet event macro:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rB As Range
    Set rB = Range("B:B").Cells.SpecialCells(xlCellTypeAllValidation)
    If Intersect(Target, rB) Is Nothing Then
    Else
        Application.EnableEvents = False
            Call Update
        Application.EnableEvents = True
    End If
End Sub

Because it is worksheet code, it is very easy to install and automatic to use:

  1. right-click the tab name near the bottom of the Excel window
  2. select View Code - this brings up a VBE window
  3. paste the stuff in and close the VBE window

If you have any concerns, first try it on a trial worksheet.

If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

To remove the macro:

  1. bring up the VBE windows as above
  2. clear the code out
  3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!



回答2:

What you are going to need is a Worksheet_Changed event similar to this:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Column("B")) Is Nothing Then
        Application.EnableEvents = False
        Call Update
        Application.EnableEvents = True
    End If
End Sub

This will trigger if any changes are made in column B. The Target is supplied by the application event and is the range that had the change made.

Edit: You will need to put this in the code of the sheet, not a module. If you right click on the sheet tab at the bottom of the excel screen, one of the options is view code.