excel vba选择最后一行和最后一列

时间:2017-04-11 18:05:27

标签: excel vba excel-vba

我正在尝试从A9选择lastrow & lastcolumn

我有这个选择最后一个单元格,但它不会从A9 to Last中选择它只选择lastrow / lastcolumn。这也不理想,因为如果我将来有空白。

我搜索过,无法找到从单元格中选择lastrow & lastcolumn

的内容
Sub FindLast()
Application.ScreenUpdating = False

Range("A9").End(xlToRight).End(xlDown).Select

Application.ScreenUpdating = True
End Sub

我的文件中的搜索顺序是列A&行8如果有帮助的话。

  

代码以下是我用于处理活动工作表的内容

Sub SelectAll()
Application.ScreenUpdating = False

Dim lastRow As Long, lastCol As Long
Dim Rng As Range
Dim WholeRng As Range

With ActiveWorksheet
    Set Rng = Cells

    'last row
    lastRow = Rng.Find(What:="*", After:=Rng.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row

    'last column
    lastCol = Rng.Find(What:="*", After:=Rng.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column

    Set WholeRng = Range(Cells(9, "A"), Cells(lastRow, lastCol))
    WholeRng.Select
End With

Application.ScreenUpdating = True
End Sub

2 个答案:

答案 0 :(得分:2)

最安全的方法是使用Find函数:

Option Explicit  

Sub LastRow_Col_Find()

    ' Safest way to ensure you got the last row:
    Dim lastRow As Long, lastCol As Long
    Dim Rng As Range
    Dim WholeRng As Range

    With Worksheets("report")   
        Set Rng = .Cells
        ' Safest way to ensure you got the last row
        lastRow = Rng.Find(What:="*", After:=Rng.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
        'MsgBox lastRow ' <-- for DEBUG

        ' Safest way to ensure you got the last column            
        lastCol = Rng.Find(What:="*", After:=Rng.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column
        'MsgBox lastColumn ' <-- for DEBUG

        ' set the Range for the entire UsedRange in "YourSheetName" sheet
        Set WholeRng = .Range(.Cells(9, "A"), .Cells(lastRow, lastCol))
        WholeRng.Select '<-- ONLY IF YOU MUST
    End With
End Sub

答案 1 :(得分:2)

或者您可以利用UsedRange

Sub FindLast()
    With Activesheet
        .Range(.Range("A9"), .UsedRange.Cells(.UsedRange.Rows.Count, .UsedRange.Columns.Count)).Select
    End With
End Sub