我要执行的操作是复制过滤范围(减去标题),但是当过滤范围未返回任何结果时,我希望它忽略。
当过滤范围内有数据时,它似乎工作正常,但是当过滤范围未返回任何结果时,我收到以下溢出错误:
调试时,它突出显示了以下代码:
If Worksheets("Cash Data (XXX)").Range("A1", Cells(Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeVisible).Count > 1 Then
这是我完整的代码:
' Filter 250000+ items (XXX)
With Workbooks("MI Dashboard.xlsm").Worksheets("Cash Data (XXX)").Range("A1")
.AutoFilter field:=15, Criteria1:="<>Inactive", Operator:=xlAnd, Criteria2:="<>Tax"
.AutoFilter field:=8, Criteria1:=">250000"
End With
' Copy to risk items workbook
Workbooks("MI Dashboard.xlsm").Sheets("Cash Data (XXX)").Activate
Dim N4 As Long
N4 = Cells(Rows.Count, "A").End(xlUp).Row
If Worksheets("Cash Data (XXX)").Range("A1", Cells(Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeVisible).Count > 1 Then
Worksheets("Cash Data (XXX)").Range("A2:I" & N4).Copy _
Destination:=Workbooks("Temp.xlsx").Sheets("Cash").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
Worksheets("Cash Data (XXX)").Range("J2:T" & N4).Copy _
Destination:=Workbooks("Temp.xlsx").Sheets("Cash").Cells(Rows.Count, 13).End(xlUp).Offset(1, -1)
Else
End If
答案 0 :(得分:1)
实际上没有结果时,您的End(xlUp)
会转到最后一行,这会给您带来溢出错误
更改行:
Worksheets("Cash Data (XXX)").Range("A1", Cells(Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeVisible).Count
使用:
Worksheets("Cash Data (XXX)").Range("A1:A" & N4).Rows.SpecialCells(xlCellTypeVisible).Count
答案 1 :(得分:0)
使用Mikku的修改后的代码,我通过从代码中取出SpecialCells(xlCellTypeVisible)
解决了溢出错误。
Mikku的代码:
IF Worksheets("Cash Data (XXX)").Range("A1:A" & N4).Rows.SpecialCells(xlCellTypeVisible).Count > 1 Then
更正代码:
If Worksheets("Cash Data (XXX)").Range("A1:A" & N4).Rows.Count > 1 Then