VBA Excel Determine if "Table##" has data
The databodyrange property of a listobject represents the range of data. if there is no data in the list object, then the range has nothing
if ws.ListObjects("Table24").DataBodyRange is Nothing then
'Do something if there is no data
Else
'Do something if there is data
end if
Answer: If WorksheetFunction.CountA(Range("Table24")) = 1 Then
Add this function (taken from here):
Function DBRRangeTest(rng1 As Range, Optional rng2 As Range)
' DataBodyRange Range Test
' Test if rng1 and rng2 intersect
If rng2 Is Nothing Then
' Either no argument was supplied or the supplied argument was empty
DBRRangeTest = False
Exit Function
End If
If (rng1.Parent.Name = rng2.Parent.Name) Then
Dim ints As Range
Set ints = Application.Intersect(rng1, rng2)
If (Not (ints Is Nothing)) Then
DBRRangeTest = True
End If
End If
End Function
Then, replace this:
If ws.Range("Table24").Rows.Count > 0 Then
Set myDataRange = ws.ListObjects("Table24").ListColumns(3).DataBodyRange
Else
Set myDataRange = ws.Range("K1")
End If
with this:
Dim tbl As ListObject
Set tbl = ws.ListObject("Table24")
If DBRRangeTest(tbl.HeaderRowRange.Offset(1), tbl.DataBodyRange) Then
' If this test returns true, it means that there is a valid databodyrange _
' but we have no guarantee whether the cell is empty or not, because DataBodyRange _
' will return with an address if there *has* been a value in its range.
' So we'll test manually.
If tbl.HeaderRowRange.Offset(1).Value <> "" Then
Set myDataRange = tbl.ListColumns(3).DataBodyRange
Else
Set myDataRange = ws.Range("K1")
End If
Else
' The test returned false, which essentially is the same as _
' DataBodyRange Is Nothing.
Set myDataRange = ws.Range("K1")
End If