简体   繁体   English

如何在Excel VBA for loop中指定多个列范围?

[英]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'. 我有以下形式的VBA for循环:对于col = 23到27,其中范围23到27指的是列“ W”到“ 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? 现在,我想为For循环添加更多不同的范围,以便它将循环显示23到27,然后是30到33,然后是40到44,等等。 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: 您可以使用Select Case语句:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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