简体   繁体   中英

How do I specify multiple ranges of columns in an Excel VBA for loop?

I have a VBA for loop in the form: For col = 23 to 27 where the range 23 to 27 refers to columns 'W' to 'AA'. I now want to add more distinct ranges to the For loop so that it will loop through 23 to 27, then 30 to 33, then 40 to 44, etc. What is a way in which I can do this? Thanks for your help!

I'd loop through the columns which are stored in an array.

Dim arrCol(1 to 3, 1 to 2)
Dim i As Integer

'Initialize array
arrCol(1,1) = 23
arrCol(1,2) = 27
arrCol(2,1) = 30
arrCol(2,2) = 33
arrCol(3,1) = 40
arrCol(3,2) = 44

'Loop through column ranges
For i = 1 to UBound(arrCol())
    Range(Columns(arrCol(i,1)),Columns(arrCol(i,2))).SomeStatement
Next

You could use a Select Case statement:

For col = 23 to 999 'or whatever
    Select Case col
        Case 23 To 27, 30 To 33, 40 To 44
            'do whatever you like here
    End Select
Next

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