簡體   English   中英

通過VB.net在Excel工作表上應用自動過濾器

[英]Applying Auto-filter on excel sheet through VB.net

我想知道哪里出了問題,我基本上想在我通過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")是我得到的。

快速方法是使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM