简体   繁体   中英

VBA Excel how can I define a set of columns using numbers?

Some of us have proposed great simple ways to define a set of columns in Excel VBA, such as:

.Union(Columns("a"), Columns("b"), Columns("d"))

Those examples are using letters to refer to those columns. I need to refer to my columns using numbers, such as in:

.Union(Columns(2), Columns(7), Columns(23)). 

The later works great but what if I need to refer to columns using a range of columns such as in:

.Union(columns(2), columns(7), columns(9 to 23)) 

The idea being that I would not have to define the .Union with each column separately, which, in the present example would necessitate 17 columns(x) listing.

Not an elegant code. Furthermore, I need to use numbers because the column numbers are determined programmatically and are changing during execution.

Thanks for your input. Cheers

您将需要使用RANGE():

.Union(.columns(2), .columns(7), .Range(.columns(9), .columns(23)))

set MyRange = worksheets("mySheet").range( columns(1), columns(5) ) works pretty well.
It actually select a range of columns from column 1 to column 5.
Further to that I can then use the Union to join other single columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM