2017-04-11 236 views
1

我试图从A9选择到lastrow & lastcolumnExcel VBA中选择最后一排和最后一列

我有这样的选择最后一个单元格,但它不会从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 
+0

首先,你可能不希望实际'选择它,请参阅[如何避免使用'.Select' /'.Activate'](https://stackoverflow.com/questions/10714251/how-to-avoid - 使用 - 选择功能于Excel的VBA的宏)。另外,你在哪里搜索?你有什么尝试?这个问题已被多次询问(请参阅右边的“相关”帖子)。 – BruceWayne

回答

2

或者你也可以利用UsedRange

Sub FindLast() 
    With Activesheet 
     .Range(.Range("A9"), .UsedRange.Cells(.UsedRange.Rows.Count, .UsedRange.Columns.Count)).Select 
    End With 
End Sub 
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 
+0

更新的代码运行完美,非常感谢! –