简体   繁体   中英

How to make a macro run with change in each cell of a dynamic table? Excel VBA

I have a table whose size is determined by the user. I need a macro to run for every time the user enters or changes a value in each cell of the 1st column.

The default table has just the header row and 1 blank row. There's a separate macro-enabled button whose function is to just add rows to this table when needed. I tried to use the test code below to first find out the size of the table and then run a macro each time a cell in the 1st column of that table changes.

Private Sub Worksheet_Change(ByVal Target As Range)

Dim dyString As String
Dim dyRange As Range
Dim LastRowEntry_1 As Integer

LastRowEntry_1 = ActiveSheet.ListObjects("TableName").Range.Rows.Count

dyString = "B12:B" & LastRowEntry_1
Set dyRange = Range(dyString)

If Not Intersect(Target.Columns(1), dyRange) Is Nothing Then
    If IsEmpty(Target.Value) = False Then
    'RUN MACRO 1
    End If
End If

End Sub

While the macro runs properly for any change in the 1st row, each time a new row is added to the table, the macro runs on just the action of adding the blank row (clicking the button) and doesn't for any subsequent changes to the cell in the new rows. I need it to run only on entering values in those cells or changing existing values and not when its blank.

Where am I going wrong?

You need to make sure your button code does not interfere with your Event macro.

Structure your button code like:

Sub ButtonCode()
    Application.EnableEvents = False
        ' your code to add rows
    Application.EnableEvents = True
End Sub

and also in your Event macro use:

If IsEmpty(Target.Value) = False Then
    Application.EnableEvents = False
         'RUN MACRO 1
    Application.EnableEvents = True
End If

I would also replace:

If IsEmpty(Target.Value) = False Then

with:

If Target.Value <> "" Then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM