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

前端 未结 11 807
萌比男神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:11

    I have found that the Worksheet ".UsedRange" method is superior in many instances to solve this problem. I struggled with a truncation issue that is a normal behaviour of the ".CurrentRegion" method. Using [ Worksheets("Sheet1").Range("A1").CurrentRegion ] does not yield the results I desired when the worksheet consists of one column with blanks in the rows (and the blanks are wanted). In this case, the ".CurrentRegion" will truncate at the first record. I implemented a work around but recently found an even better one; see code below that allows copying the whole set to another sheet or to identify the actual address (or just rows and columns):

    Sub mytest_GetAllUsedCells_in_Worksheet()
        Dim myRange
    
        Set myRange = Worksheets("Sheet1").UsedRange
        'Alternative code:  set myRange = activesheet.UsedRange
    
       'use msgbox or debug.print to show the address range and counts
       MsgBox myRange.Address      
       MsgBox myRange.Columns.Count
       MsgBox myRange.Rows.Count
    
      'Copy the Range of data to another sheet
      'Note: contains all the cells with that are non-empty
       myRange.Copy (Worksheets("Sheet2").Range("A1"))
       'Note:  transfers all cells starting at "A1" location.  
       '       You can transfer to another area of the 2nd sheet
       '       by using an alternate starting location like "C5".
    
    End Sub
    

提交回复
热议问题