2017-07-17 76 views
2

如何始终在With xx end With中检测隐藏的列和行?我的代码的当前变量值取决于隐藏或不隐藏的行和行。这阻止了我的代码正常工作。VBA Excel在With x End With循环中检测始终隐藏的行和列?

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 

回答

0

得到最后的行/列的也当它们被隐藏:

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

如果您需要特定的栏目,如下所示:

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

+0

嗨,你的例子计算工作表中所有可能的行。我只想要最后一行是文本。 – AratioD

+1

@AratioD将'Cells'部分更改为您使用的范围...像'Columns(3)' –

2

我发现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解决方案在@Vityata提供的链接中进行介绍。