VBA - Select columns using numbers?

前端 未结 9 2187
北荒
北荒 2021-02-05 08:06

I\'m looking for an alternative to this code, but using numbers. I want to select 5 columns, the start column is a variable, and then it selects 5 columns from this

相关标签:
9条回答
  • 2021-02-05 08:38

    Try using the following, where n is your variable and x is your offset (4 in this case):

    LEFT(ADDRESS(1,n+x,4),1)
    

    This will return the letter of that column (so for n=1 and x=4, it'll return A+4 = E). You can then use INDIRECT() to reference this, as so:

    COLUMNS(INDIRECT(LEFT(ADDRESS(1,n,4),1)&":"&LEFT(ADDRESS(1,n+x,4),1)))
    

    which with n=1, x=4 becomes:

    COLUMNS(INDIRECT("A"&":"&"E"))
    

    and so:

    COLUMNS(A:E)
    
    0 讨论(0)
  • 2021-02-05 08:38

    In this way, you can start to select data even behind column "Z" and select a lot of columns.

    Sub SelectColumNums()
        Dim xCol1 As Integer, xNumOfCols as integer
        xCol1 = 26
        xNumOfCols = 17
        Range(Columns(xCol1), Columns(xCol1 + xNumOfCols)).Select
    End Sub
    
    0 讨论(0)
  • 2021-02-05 08:39

    You can specify addresses as "R1C2" instead of "B2". Under File -> Options -> Formuals -> Workingg with Formulas there is a toggle R1C1 reference style. which can be set, as illustrated below.

    enter image description here

    0 讨论(0)
提交回复
热议问题