Home > OS >  VBA - to clear table based on number of rows
VBA - to clear table based on number of rows

Time:09-15

I'm trying to clear Table "A" - based on number of rows present in Table "A"

For example if there is less than 2 rows present in Table "A" then clear all contents in Table "A"

with sheets("DOC").ListObjects("A")
if A.Rows.Count > 2 Then
A.databodyrange.ClearContents
ENDif
ENDwith

I know for sure this wrong because it keeps giving me an error. Wondering how to fix this or if there is a better way.

any help would be apreciated.

CodePudding user response:

A ListObject has a ListRows property:

With Sheets("DOC").ListObjects("A")
   If .ListRows.Count < 2 Then
       .DataBodyRange.ClearContents
   End If
End With

Also, if you want to check for fewer than 2 rows, then use <, not >.

However, if a table has 0 .ListRows, then its .DataBodyRange is Nothing. So, maybe better to check if it has only 1 row.

With Sheets("DOC").ListObjects("A")
   If .ListRows.Count = 1 Then
       .DataBodyRange.ClearContents
   End If
End With
  • Related