How do you select the entire excel sheet with Range using VBA?

前端 未结 11 591
萌比男神i
萌比男神i 2021-02-01 16:37

I found a similar solution to this question in c# How to Select all the cells in a worksheet in Excel.Range object of c#?

What is the process to do this in VBA?

11条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 17:21

    you have a few options here:

    1. Using the UsedRange property
    2. find the last row and column used
    3. use a mimic of shift down and shift right

    I personally use the Used Range and find last row and column method most of the time.

    Here's how you would do it using the UsedRange property:

    Sheets("Sheet_Name").UsedRange.Select
    

    This statement will select all used ranges in the worksheet, note that sometimes this doesn't work very well when you delete columns and rows.

    The alternative is to find the very last cell used in the worksheet

    Dim rngTemp As Range
    Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
    If Not rngTemp Is Nothing Then
        Range(Cells(1, 1), rngTemp).Select
    End If
    

    What this code is doing:

    1. Find the last cell containing any value
    2. select cell(1,1) all the way to the last cell

提交回复
热议问题