Insert new row on top in a table when a certain cell is populated

ProbioT

New member
Joined
Jan 12, 2019
Messages
10
Reaction score
0
Points
1
Excel Version(s)
2007
Hello everyone,
Can someone help me with this, please:

I have a table with columns A, B, C, D, E. The table header is in the first row of the Sheet (A1: E1).
I'd like to know VBA code to insert a new blank row on the top in the table each time when the cell E2 is populated.
Thanks a bunch.
 
Try the Worksheet_Change event in the sheet module
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Count > 1 Then Exit Sub
    If Target.Address = "$E$2" And Target <> "" Then
        Application.EnableEvents = False
        ActiveSheet.ListObjects(1).ListRows.Add (1)
        Application.EnableEvents = True
        'position cursor
        ActiveSheet.ListObjects(1).DataBodyRange(2, 1).Select
    End If
End Sub

some info about tables:
https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables
 
@Nos: Thanks for your suggestion. It did not work for some reasons.
I Run Sub (F5) and a window pops up where I need to select a macro.
I did not have any recorded macros to do it. So, I created this one:

Sub AddTopRow()

' AddTopRow Macro

Rows("2:2").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("E2").Select
Selection.ClearContents
End Sub

This still wont't work as expected (when "E2" populated a new top row needs to be inserted).
Any other suggestion?
My apologies, I an a newbie in Excel with a lot of passion for it.
Thanks again.

Try the Worksheet_Change event in the sheet module
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Count > 1 Then Exit Sub
    If Target.Address = "$E$2" And Target <> "" Then
        Application.EnableEvents = False
        ActiveSheet.ListObjects(1).ListRows.Add (1)
        Application.EnableEvents = True
        'position cursor
        ActiveSheet.ListObjects(1).DataBodyRange(2, 1).Select
    End If
End Sub

some info about tables:
https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables
 
Hi,
When posting code, please wrap it with code tags ( Edit code - select code - click the #button.)
It keeps the macro's structure and makes it easy to copy and handle.
Thank you
 
You are awesome NoS. Thank you, thank you so much.
You made my day.
 
@Pecoflyer: My sincere apologies for it. I miss it. Sorry.
 
Last edited:
Back
Top