我想知道哪里出了问题,我基本上想在我通过vb.net打开的excel工作表上应用自动过滤器,然后读取经过过滤的数据。
我已经阅读了几乎所有与vb / autofilter相关的答案,但是我肯定做错了什么,但似乎可以发现它!
xlWorkSheet = xlWorkBook.Sheets(2)
xlWorkSheet.Name = "ACC"
xlWorkSheet.Range("$A$4:$AE$4480").AutoFilter(Field:=31, Criteria1:="=Accepted")
xlCell = xlWorkSheet.UsedRange
intLstRowIdx = xlWorkSheet.Range("A" & xlWorkSheet.Rows.Count).End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row
For rcnt = intLstRowIdx To 2 Step -1
Dim Obj = CType(xlCell.Cells(rcnt, 31), excel.Range)
If Obj.Text.ToString.ToUpper.Contains("ACC") = True Then
xlWorkSheet.Rows(rcnt).Delete()
End If
Next
我希望这样做是将过滤器应用于Excel工作表,然后基本上使所有我的记录/行成为其中第31列已“接受”的记录/行,因此我将尝试更改删除行部分以更快地进行删除,例如删除范围等。
但是当我运行上面的代码时,它就运行了,但它似乎并没有保留甚至运行过滤器,因为“拒绝”记录仍显示在我的for循环等中。
我非常感谢任何帮助人员,我确实已经尝试过加载,只是知道这是我愚蠢而单行遗漏或在代码中与自己矛盾。
修改
我已经使用excel记录了在excel中执行过滤器的宏,而行xlWorkSheet.Range("$A$4:$AE$4480").AutoFilter(Field:=31, Criteria1:="=Accepted")
就是我得到的。
答案 0 :(得分:1)
快速方法是使用SpecialCells
获取所有过滤范围。获取后,您可以删除一行中的所有行:
Dim rngTable, rngData, rngVisible As Excel.Range
'// Original data
rngTable = xlWorkSheet.Range("$A$4:$AE$4480")
'// Exclude header - we don't want it to take a part in filtering
With rngTable
'// Offset range by one row and then resize it excluding last row.
'// This way we obtain all cells without header.
rngData = rngTable.Offset(1).Resize(.Rows.Count - 1)
End With
'// Filtering
rngData.AutoFilter(Field:=31, Criteria1:="=Accepted")
Try
'// SpecialCells takes all visible cells (i.e. filtered), which is what we need.
'// We need to use it in Try..Catch because if there are no filtered cells,
'// this method will throw exception.
rngVisible = rngData.SpecialCells(Excel.XlCellType.xlCellTypeVisible)
'// Having obtained all cells, delete entire rows.
rngVisible.EntireRow.Delete()
Catch ex As Exception
'// We're here 'cause no rows were filtered
End Try