Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete Last Row in Table vba

Hi have used the below code to remove the last row of data from a table. The code works ok in isolation but when run as part of a larger set of code it does not remove the last row. Any ideas on what is causing this and solution would be appreciated.

Sub TrimJrnl()
    
    Dim wsR2 As Worksheet
    
    Set wsR2 = ThisWorkbook.Sheets("Journal")
    
    lastrow = wsR2.ListObjects("xJrnl").Range.rows.Count
    
    rows(lastrow).Delete
    
End Sub

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. You need to count the rows of ListObjects("xJrnl").DataBodyRange so you know how many data rows are there (except header and summary rows).

  2. You can access those data rows by ListObjects("xJrnl").ListRows(LastRow) and .Delete them.

Like Below:

Option Explicit

Public Sub TrimJrnl()
    Dim wsR2 As Worksheet
    Set wsR2 = ThisWorkbook.Sheets("Journal")
    
    Dim LastRow As Long
    LastRow = wsR2.ListObjects("xJrnl").DataBodyRange.Rows.Count
    
    wsR2.ListObjects("xJrnl").ListRows(LastRow).Delete
End Sub

A nice guide how to work with tables: The VBA Guide To ListObject Excel Tables

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading