vba for循环,loop循环

(1)For Next语句  以指定次数来重复执行一组语句

For counter = start To end [Step step]                  'step 缺省值为1
[statements]
[Exit For]’退出for循环
[statements]
Next [counter]

 

如:

For Words = 10 To 1 Step  -1                               '建立 10 次循环 
      For Chars = 0 To 9                                        '建立 10 次循环
           MyString = MyString & Chars                      '将数字添加到字符串中
      Next Chars                                                   'Increment counter
      MyString = MyString & " "                                '添加一个空格
Next  Words

 

使用for递减循环删除excel的行时,正着删除行数会发生变化,倒着删除即可解决这个问题

 

 (2)For Each…Next 语句  主要功能是对一个数组或集合对象进行,让所有元素重复执行一次语句

For Each element In  group
Statements
[Exit for]
Statements
Next  [element]

如:

For Each rang2 In  range1
     With range2.interior
             .colorindex=6
             .pattern=xlSolid
     End with
Next

 

(3)Do…loop语句 在条件为true时,重复执行区块命令

Do {while |until} condition' while 为当型循环,until为直到型循环,顾名思义,不多说啦
Statements
Exit do
Statements
Loop

或者使用下面语法:

Do                                    ' 先do 再判断,即不论如何先执行一次
Statements
Exit do
Statements
Loop {while |until} condition

 

posted @ 2023-03-07 11:46  绮丽梦境  阅读(401)  评论(0编辑  收藏  举报