I have a segment of VBA that looks to autofilter out all the rows in which column 37 is blank. It works great, EXCEPT when there is nothing in the column for the entire data set. Then, instead of filtering away everything but the header row, autofilter does not filter any rows out. This results in the adding of the comment "Expected Waste to all the rows instead of just the ones with a value in column 37. Code is below. Any help on what I am doing wrong would be much appreciated.
' Filter Data by ExpectedWaste
Sheets("Data").Columns("A:AQ").AutoFilter Field:=37, Criteria1:="<>"
' Add expected Waste comment
Sheets("Data").Range("AQ2:AQ" & lastRow).FormulaR1C1 = "Expected waste"
' Unfilter Data
If (Sheets("Data").AutoFilterMode And Sheets("Data").FilterMode) Or
Sheets("Data").FilterMode Then
Sheets("Data").ShowAllData
End If
答案 0 :(得分:1)
Typically, I test for visible cells before performing any actions.
with Sheets("Data").Cells("A1:AQ" & lastRow)
.AutoFilter Field:=37, Criteria1:="<>"
with .resize(.rows.count-1, .columns.count).offset(1, 0)
if cbool(application.subtotal(103, .cells)) then
'perform actions on .Specialcells(xlcelltypevisible) here
.columns("AQ").Specialcells(xlcelltypevisible).value = "Expected waste"
end if
end with
end with
答案 1 :(得分:0)
我认为AutoFilter
不适用于空白列。检查是否有任何要首先过滤的内容,Cells(Rows.Count, 37).End(xlUp).Row > 1
行,因为否则您编写的代码Sheets("Data").Range("AQ2:AQ" & lastRow).FormulaR1C1 = "Expected waste"
将填满整个列。