I have a worksheet change event that performs an action when each cell of a table column changes. For that specific action, I need to find the row number of the target cell. I have the following snippet inside the Worksheet_Change event:
If Not Intersect(Target, tbl.ListColumns(5).DataBodyRange) Is Nothing Then
Application.EnableEvents = False
row_num = tbl.ListRows(Target.Row - tbl.HeaderRowRange.Row).Index
Application.EnableEvents = True
End If
I have a separate macro that just refreshes this same table on a button click.
Sub Refresh()
Application.EnableEvents = False
ActiveSheet.ListObjects("Table1").Refresh
Application.EnableEvents = True
End Sub
The macro runs fine and returns the right row_num. However, only when the table is refreshed, the Target.Row value in the 1st snippet is set to the same row number as the Header row of that table, thus making row_num as empty and returning a 'Subscript out of range error.
Why is this happening? By specifying that the action be performed only when the target cell intersects the DataBodyRange of that table column, should it not work only for changes in the data part of the column (excluding header and totals)?
Debug.Print Target.Row(outside the loop), it doesn't return the correct row number?Target.Rowis the same row number as the header row of the table. Is that true or not? In other words, do you have sample values forTarget.Rowandtbl.HeaderRowRange.Row?Target.Rowis somehow detected as the Header Row cell and an error is returned because of the wayrow_num(the table row number) is calculated and it results inrow_num=0. The macro runs fine if I don't refresh -Target.Rowreturns the sheet row number of the changed cell, using which the rightrow_numis identified.