2013-04-18 49 views
4

我有一个过滤表(在代码中作为ListObject)的宏,然后将DataBodyRange中的可见单元复制到一个单独的表中。代码工作正常,除非过滤动作删除所有数据(即表只有标题行,而没有其他)。Excel VBA - 检查过滤的表是否返回任何结果

是否有一个简洁的方式来检查是否有任何行可见?如果可能的话,我想尽量避免使用on error resume条款,但我正在努力想方设法?

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

亚当

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

尝试访问'TargetT'时出现1004错误able.DataBodyRange.SpecialCells(xlCellTypeVisible)'范围,对吧? –

回答

4

使用表的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 
+0

不起作用,我也查过了!把一些过滤,留下几个记录,并检查... –

+0

应该> 1,不> = 1 ...刚刚修改! –

+0

仅返回2个值:1或ListObject总行数。而1是在你几乎没有过滤结果的情况下......这也是我的思考方式,但也不工作.... :) –

1

一种替代方法将是比较.SpecialCells(xlCellTypeVisible).Address到标题行地址,tbl.HeaderRowRange.Address

这里是大卫的代码的变化:

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 
1

只是检查Range.Height不为0:

If [Table1].Height Then 

此外,当.Height大于0不需要.SpecialCells(xlCellTypeVisible)

If TargetTable.DataBodyRange.Height Then TargetTable.DataBodyRange.Copy OutputPasteRange 
相关问题