
本文于2023年9月20日首发于本人同名其他平台,更多文章案例请搜索关注!
内容提要
VBA循环语句
大家好,我是冷水泡茶,我们已经分享了不少Excel VBA案例,今天我们稍微总结一下,谈谈VBA的循环语句问题。
闲话少叙,我就直接进入正题吧:
For...Next循环:
我们常用的是以数字进行循环:
for i=1 to 10 ......next
还有,在一个对象集合里面:
for each a in b ......next
我们看几个例子
1、循环工作表:
Sub 循环工作表() Dim ws As Worksheet For Each ws In Sheets i = i + 1 Debug.Print "这是第" & i & "张表,名称为:" & ws.Name NextEnd Sub

2、循环单元格:
Sub 循环单元格() Dim ws As Worksheet Dim rng As Range Dim cell As Range Set ws = ThisWorkbook.Sheets("表3") Set rng = ws.Range(Cells(1, 1), Cells(10, 10)) For Each cell In rng If cell.Row = cell.Column Then cell.Interior.Color = vbRed Else cell.Value = 1 End If NextEnd Sub
3、循环删除空白行:
Sub 循环删除空白行() Dim ws As Worksheet Dim lastRow As Integer Set ws = ThisWorkbook.Sheets("表3") With ws lastRow = .UsedRange.Rows.Count For i = lastRow To 1 Step -1 If .Cells(i, 1) = "" Then Rows(i).Delete End If Next End WithEnd Sub
4、循环数组
Sub 循环数组() Dim ws As Worksheet Dim lastRow As Integer Dim lastCol As Integer Dim arr(), str As String Set ws = ThisWorkbook.Sheets("表2") With ws lastRow = .UsedRange.Rows.Count lastCol = .UsedRange.Columns.Count arr = .Range(.Cells(1, 1), .Cells(lastRow, lastCol)).Value For i = LBound(arr) To UBound(arr) For j = LBound(arr) To UBound(arr, 2) str = str & "|" & arr(i, j) Next Debug.Print str str = "" Next End WithEnd Sub
5、循环字典
Sub 循环字典() Dim ws As Worksheet Dim lastRow As Integer Dim lastCol As Integer Dim arr(), str As String Dim dic As Object, dKey As String Dim key As Variant Set dic = CreateObject("Scripting.Dictionary") Set ws = ThisWorkbook.Sheets("表1") With ws lastRow = .UsedRange.Rows.Count lastCol = .UsedRange.Columns.Count arr = .Range(.Cells(2, 1), .Cells(lastRow, lastCol)).Value For i = LBound(arr) To UBound(arr) dKey = arr(i, 1) dic(dKey) = dic(dKey) + arr(i, 2) Next End With For Each key In dic.keys str = str & key & ":" & dic(key) & Chr(10) Next Debug.Print strEnd Sub
6、循环工作表中的控件:
Sub 循环工作表中的控件() Dim ws As Worksheet Dim obj As OLEObject Dim top As Integer Set ws = ThisWorkbook.Sheets("表1") top = 5 For Each obj In ws.OLEObjects top = top + obj.Height obj.top = top obj.Left = 150 NextEnd Sub
7、循环用户窗体中的控件:

Private Sub CommandButton1_Click() Dim ctr As Control Dim top As Integer For Each ctr In Me.Controls If ctr.Name Like "CheckBox*" Then top = top + ctr.Height + 5 i = i + 1 ctr.top = top ctr.Left = 10 ctr.Caption = "复选框" & i If i Mod 2 Then ctr.Value = True End If End If NextEnd Sub

我们常用的For循环大概就列举这么多。
Do While循环
基本结构:
Do While 条件(条件为真,继续执行循环) ......Loop
我们举一个例子:
Sub DoWhile循环() Dim m As Integer Do While m < 100 m = m + 1 Debug.Print m LoopEnd Sub

Do Until循环
基本结构:
Do Until 条件(条件为真,退出循环) ......Loop
我们举一个例子:
Sub DoUntil循环() Dim m As Long m = 1 Do Until m > 1000 m = m * 2 Debug.Print m LoopEnd Sub

总结
1、循环语句是编程中的一个必不可少的方法,可以说没有循环,就根本无法编程。
2、我们用的比较多的是For...Next结构的循环,有下标等数字序列的,我们就用数字来循环。以数字区间进行循环的,有个参数我们常常省略,就是步长Step,默认为1。如果步长不是1,则不能省略,像上面删除空白行的例子中,我们是从大数字向小数字循环,步长为-1;Exit For,条件满足跳出循环。
3、还有一些例子我们没有举,比如循环记录集,循环用户窗体等。
~~~~~~End~~~~~~
喜欢就点个赞、点在看、留个言、分享一下呗!感谢!