VBA - Select columns using numbers?

前端 未结 9 2189
北荒
北荒 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:14

    Columns("A:E").Select
    

    Can be directly replaced by

    Columns(1).Resize(, 5).EntireColumn.Select
    

    Where 1 can be replaced by a variable

    n = 5
    Columns(n).Resize(, n+4).EntireColumn.Select
    

    In my opinion you are best dealing with a block of columns rather than looping through columns n to n + 4 as it is more efficient.

    In addition, using select will slow your code down. So instead of selecting your columns and then performing an action on the selection try instead to perform the action directly. Below is an example to change the colour of columns A-E to yellow.

    Columns(1).Resize(, 5).EntireColumn.Interior.Color = 65535
    

提交回复
热议问题