2017-04-11 226 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

更新的代碼運行完美,非常感謝! –