Forum Discussion
Dont display table if empty
is there a way to clear the table if there is no more than 2 rows in the table using VBA?
I know how to clear the worksheet but not sure how to clear the specific table based on the condition.
Hi jijoythomas29,
the code itselfis fairly simple:
Private Sub Workbook_ModelChange(ByVal Changes As ModelChanges)
tblExists = False
If Changes.TablesModified.Count > 0 Then Exit Sub
On Error Resume Next
tblExists = ActiveSheet.ListObjects("Query1").Name = "Query1"
On Error GoTo 0
If tblExists Then
ActiveSheet.ListObjects("Query1").Refresh
Else
With ActiveSheet.ListObjects.Add(SourceType:=4, Source:=ActiveWorkbook. _
Connections("Query - Query1"), Destination:=Range("$A$2")).TableObject
.RowNumbers = False
.PreserveFormatting = True
.RefreshStyle = 1
.AdjustColumnWidth = True
.ListObject.DisplayName = "Query1"
.Refresh
End With
End If
If ActiveSheet.ListObjects("Query1").Range.Rows.Count < 3 Then ActiveSheet.ListObjects("Query1").Delete
End SubAbove, we check if the table exists (cos we gong to delete the emplty this may not be the case) and delete it. Then we add it back and check how may rows it has, if only two then we delete it. Just change the code to your Workbook section of your VBA code. It will run on RefreshAll, but you will need to initially set the query to feed to your Data model in the Excel file (using Load To...).
Do you want to make the file macro-enabled only for this benefit?
Kind regards,
John
- jbwtp3 years agoMemorable Member
And if you have any other tables in the file, the code may nee dto be updated to let them refresh correctly. I did not tested that.