簡體   English   中英

Excel VBA選擇最后一行和最后一列

[英]excel vba select last row and last column

我正在嘗試從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

最安全的方法是使用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

或者您可以利用UsedRange

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

暫無
暫無

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

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