VBA: Selecting range by variables

前端 未结 6 896
甜味超标
甜味超标 2020-12-02 21:28

I want to select the formatted range of an Excel sheet. To define the last and first row I use the following functions:

lastColumn = ActiveSheet.UsedRange.Co         


        
6条回答
  •  無奈伤痛
    2020-12-02 22:14

    I recorded a macro with 'Relative References' and this is what I got :

    Range("F10").Select
    ActiveCell.Offset(0, 3).Range("A1:D11").Select
    

    Heres what I thought : If the range selection is in quotes, VBA really wants a STRING and interprets the cells out of it so tried the following:

    Dim MyRange as String
    MyRange = "A1:D11"
    Range(MyRange).Select
    

    And it worked :) ie.. just create a string using your variables, make sure to dimension it as a STRING variables and Excel will read right off of it ;)

    Following tested and found working :

    Sub Macro04()
    
    Dim Copyrange As String
    
    Startrow = 1
    Lastrow = 11
    Let Copyrange = "A" & Startrow & ":" & "D" & Lastrow
    Range(Copyrange).Select
    End Sub
    

提交回复
热议问题