VBA Excel检测始终隐藏的行和列With x End With循环?

如何始终检测With xx end With还隐藏的列和行? 我的代码的当前variables值正在改变,取决于是否隐藏列和行。 这阻止了我的代码正常工作。

 With myMatrixSheet lastRow = .Range("B" & .Rows.Count).End(xlUp).row lastColumn = .Cells(7,.UsedRange.Columns.Count).End(xlToLeft).column + 1 End With 

我的解决和最终代码看起来像下面

 With myMatrixSheet If Application.WorksheetFunction.CountA(.Cells) <> 0 Then lastRow = .Cells.Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).row Else lastRow = 1 End If If Application.WorksheetFunction.CountA(.Cells) <> 0 Then lastColumn = .Cells.Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False).column Else lastColumn = 1 End If End With 

我发现find最简单的方法(其他方法可用):

 Sub Test() Dim LastRow As Long Dim LastColumn As Long With Sheet1 LastRow = .Cells.Find(What:="*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Row LastColumn = .Cells.Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Column End With If LastRow = 0 Then LastRow = 1 If LastColumn = 0 Then LastColumn = 1 '--OR USE SEPARATE FUNCTION-- Dim rLastCell As Range Set rLastCell = LastCell(Sheet1) Debug.Print rLastCell.Row & " : " & rLastCell.Column End Sub Public Function LastCell(wrkSht As Worksheet) As Range Dim lLastCol As Long, lLastRow As Long On Error Resume Next With wrkSht lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row If lLastCol = 0 Then lLastCol = 1 If lLastRow = 0 Then lLastRow = 1 Set LastCell = .Cells(lLastRow, lLastCol) End With On Error GoTo 0 End Function 

FIND解决scheme将覆盖@Vityata提供的链接。

当它们被隐藏时也要获得最后一行/列:

Activesheet.cells.SpecialCells(xlCellTypeLastCell).Row Activesheet.cells.SpecialCells(xlCellTypeLastCell).Column

如果您需要特定列,请使用如下所示:

 Public Function GetLastRow(lngCol As Long) As Long GetLastRow = ActiveSheet.Columns(3).Find(What:="*", SearchDirection:=xlPrevious).Row End Function 

一般来说,这可能是最后一行和最后一列的最佳文章: https : //www.rondebruin.nl/win/s9/win005.htm