Excel VBA – 检查过滤的表是否返回任何结果

我有一个macros筛选表(在代码中作为ListObject),然后将DataBodyRange中的可见单元格复制到一个单独的表。 代码工作正常,除非过滤操作删除所有的数据(即表只有标题行,没有别的)。

有没有一个简洁的方法来检查是否有可见的行? 如果可能的话,我想尽可能地避免on error resume条款,但我正在努力想办法吗?

我在下面列出了一些伪代码来说明我的意思,任何援助将不胜感激!

亚当

 If TargetTable.DataBodyRange.VisibleRows.Count > 0 Then TargetTable.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy Destination:=OutputPasteRange End If 

使用表的Range对象,而不是DataBodyRange 。 然后,检查以确保.SpecialCells(xlCellTypeVisible).Rows.Count > 1

 Sub TestEmptyTable() Dim tbl As ListObject Dim outputPasteRange As Range Dim tblIsVisible As Boolean Set tbl = ActiveSheet.ListObjects(1) Set outputPasteRange = Range("B15") If tbl.Range.SpecialCells(xlCellTypeVisible).Areas.Count > 1 Then tblIsVisible = True Else: tblIsVisible = tbl.Range.SpecialCells(xlCellTypeVisible).Rows.Count > 1 End If If tblIsVisible Then tbl.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy _ Destination:=outputPasteRange Else: MsgBox tbl.Name & " has been filtered to no visible records", vbInformation End If End Sub 

另一种方法是将.SpecialCells(xlCellTypeVisible).Address与标题行地址tbl.HeaderRowRange.Address

这是David的代码的一个变种:

 Sub TestEmptyTable() Dim tbl As ListObject Dim outputPasteRange As Range Dim tblIsVisible As Boolean Set tbl = ActiveSheet.ListObjects(1) Set outputPasteRange = Range("B15") tblIsVisible = tbl.Range.SpecialCells(xlCellTypeVisible).Address <> _ tbl.HeaderRowRange.Address If tblIsVisible Then tbl.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy _ Destination:=outputPasteRange Else MsgBox tbl.Name & " has been filtered to no visible records", vbInformation End If End Sub