Excel VBA 基础:循环与条件判断
理解VBA中的For循环、Do循环和If语句,实现数据自动化处理。 · 难度:入门 · +15XP
VBA 循环与条件判断
VBA(Visual Basic for Applications)是Excel的宏语言。掌握循环和条件语句是编写高效自动化脚本的关键。你可以用它们遍历行、检查数据并执行操作。
For循环
用于已知次数的重复操作。例如,将A1到A10每个单元格的值乘以2并写入B列:
Sub 加倍()
Dim i As Integer
For i = 1 To 10
Cells(i, 2).Value = Cells(i, 1).Value * 2
Next i
End SubDo循环
用于条件未知的循环。例如,向下遍历直到遇到空单元格:
Sub 累加()
Dim r As Integer
Dim total As Double
r = 1
Do While Cells(r, 1).Value <> ""
total = total + Cells(r, 1).Value
r = r + 1
Loop
MsgBox "合计: " & total
End SubIf条件判断
结合循环实现智能处理。例如,将A列中大于100的值标记为“高”:
Sub 标记高值()
Dim i As Integer
For i = 1 To 10
If Cells(i, 1).Value > 100 Then
Cells(i, 2).Value = "高"
Else
Cells(i, 2).Value = "低"
End If
Next i
End Sub综合示例:清理空白行
遍历第1列,如果单元格为空则删除整行(注意从下往上遍历避免序号错乱):
Sub 删除空白行()
Dim lastRow As Long
Dim i As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For i = lastRow To 1 Step -1
If Cells(i, 1).Value = "" Then
Rows(i).Delete
End If
Next i
End Sub练习提示
编写一个VBA宏,从第1行开始遍历A列,如果单元格包含“完成”字样,则将对应B列单元格填充为绿色(ColorIndex=4)。要求使用For循环和If InStr函数。