簡體   English   中英

查找最后一列和行

[英]Find last column and row

有人可以解釋如何閱讀下面的代碼嗎? 我了解我們正在尋找最后一列和最后一行,但我不清楚。

Set plage = .Range("a1:a" & .Cells.Find("*", , , , xlByRows, xlPrevious).Row)

plage.Offset(1).Resize(plage.Rows.Count - 1).EntireRow.SpecialCells(xlCellTypeVisible).Delete

這個

.Cells.Find("*", , , , xlByRows, xlPrevious).Row

使用Range.Find 方法並查看整個工作表的所有單元格.Cells並嘗試找到"*" ,這意味着找到任何東西。 xlByRows為搜索順序,即按行搜索, xlPrevious為搜索方向,即向后搜索。

因此,它會嘗試從工作表的末尾開始在工作表行的所有單元格中向后查找任何非空的內容。 這將最終出現在工作表的最后一個使用的單元格中,並且.Row返回該單元格的行號。

Set plage = .Range("a1:a" & .Cells.Find("*", , , , xlByRows, xlPrevious).Row)

所以plage是從 A1 到最后使用的行的范圍。

plage.Offset(1).Resize(plage.Rows.Count - 1).EntireRow.SpecialCells(xlCellTypeVisible).Delete

然后.Offset(1)將從該范圍偏移 1 行。 如果 plage 在偏移后是A1:A10 ,則為A2:A11 然后.Resize(plage.Rows.Count - 1)將其大小調整為比plage的行數少 1 行,使其成為A2:A10 這一切的目的是從這個范圍中刪除 header 行。 最后.EntireRow使其成為整行,因此第 2 到 10 行2:10.SpecialCells(xlCellTypeVisible)將僅采用該范圍內的可見單元格並.Delete它們。


整個代碼對我來說看起來有點過於復雜,你可以更容易地達到完全相同的效果。

Set plage = .Range("2:" & .Cells.Find("*", , , , xlByRows, xlPrevious).Row)

這將使plage直接變為2:10 ,而無需使用整行、偏移和調整大小,因此您只需要從中取出可行的單元格並將其刪除。

plage.SpecialCells(xlCellTypeVisible).Delete

請注意,如果沒有可見單元格, SpecialCells(xlCellTypeVisible)可能會引發錯誤。 所以我建議做一些錯誤處理:

Dim CellsToDelete As Range
On Error Resume Next  ' hide all error messages because the next line might throw an error
Set CellsToDelete = plage.SpecialCells(xlCellTypeVisible)
On Error Goto 0  ' re-enable error reporting!

If Not CellsToDelete Is Nothing Then
    CellsToDelete.Delete
Else
    MsgBox "There are no visible cells to delete.", vbInformation
End If

查找和自動篩選

  • 只是解決一些小問題。
Option Explicit

Sub FindAutoFilter()
    
    Dim plage As Range
    With ThisWorkbook.Worksheets("Sheet1")
        ' The 'Find' method may (will) fail if the worksheet is filtered
        '.AutoFilterMode = False
        Dim lCell As Range
        ' xlFormulas will allow hidden rows, xlValues may fail.
        Set lCell = .Cells.Find("*", , xlFormulas, , xlByRows, xlPrevious)
        If lCell Is Nothing Then Exit Sub
        Set plage = .Range("A1:A" & lCell.Row)
    End With
    
    ' e.g.:
    plage.AutoFilter Field:=1, Criteria1:="Delete"
    ' The following makes sense only with the previous. Note the slight
    ' inaccuracy: in this case you should first resize, then offset.
    plage.Resize(plage.Rows.Count - 1).Offset(1) _
        .EntireRow.SpecialCells(xlCellTypeVisible).Delete

End Sub

暫無
暫無

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

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