简体   繁体   中英

Excel: Adding new row to bottom of table, when there are two tables (vertically) in the same worksheet

I have a problem which is probably very easy for you to help me solve.

I have two tables: Table1 and Table2. Both tables are in the same worksheet called "Budget".

I want to add a command button / a plus button, that enables a user to add a new row at the bottom of each table.

However, after trying this via the macro record function, I recognized that at some point, the new rows of Table2 are added somewhere in the middle, after having added several new rows to Table1.

Can someone please provide me with a code, that solves this issue and sort of auto-adjusts?

I have never in my life coded something.

Thank you in advance for your help!

Code from recorder:

Sub NEWROW() 
' 
' NEWROW Makro 
' 
' 
Range("B12:C12").Select 
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove 
End Sub

Try this code

Option Explicit

Sub AddRows()
    Dim wks As Worksheet
    Dim tbl1 As ListObject
    Dim tbl2 As ListObject


    Set wks = ActiveSheet

    Set tbl1 = wks.ListObjects("Table1")
    Set tbl2 = wks.ListObjects("Table2")

    tbl1.ListRows.Add
    tbl2.ListRows.Add

End Sub

Table object is explained here

Update Ok, for an absolute beginner this might be the easiest way to do it.

Sub AddRowTbl1()
    Dim wks As Worksheet
    Dim tbl As ListObject
    Set wks = ActiveSheet

    Set tbl = wks.ListObjects("Table1")
    tbl.ListRows.Add

End Sub

Sub AddRowTbl2()
    Dim wks As Worksheet
    Dim tbl As ListObject

    Set wks = ActiveSheet

    Set tbl = wks.ListObjects("Table2")

    tbl.ListRows.Add
End Sub

PS A more advanced user would use a function

Function tblAddRow(tblname As String, wks As Worksheet)

Dim tbl As ListObject

    On Error GoTo EH

    Set tbl = wks.ListObjects(tblname)
    tbl.ListRows.Add

EH:

End Function

Sub Test_tblAdd()
    tblAddRow "Table1", ActiveSheet
End Sub

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