VBA 中的各种循环
利用循环和分支语句判断 B 列数字的符号,将结果填入 C列。
原始表格如如下:
1、For 循环和 If 语句,代码如下:
Sub sign()
Dim sign As String, i As Integer '声明变量
For i = 3 To 13 Step 1
If Cells(i, "B") < 0 Then
sign = "负数"
ElseIf Cells(i, "B") > 0 Then
sign = "正数"
Else
sign = "零"
End If
Cells(i, "C") = sign '向 C 列对应单元格中写入数据
Next i
End Sub
运行代码,结果如下:
2、For 循环和 Select Case 语句,代码如下:
Sub sign()
Dim sign As String, i As Integer '声明变量
For i = 3 To 13 Step 1
Select Case Cells(i, "B")
Case Is < 0
sign = "负数"
Case Is > 0
sign = "正数"
Case Else
sign = "零"
End Select
Cells(i, "C") = sign '向 C 列对应单元格中写入数据
Next i
End Sub
3、Do While 循环和 Select Case 语句, 代码如下:
Sub sign()
Dim sign As String, i As Integer '声明变量
i = 3 '初始化循环变量
Do While Cells(i, "B") <> ""
Select Case Cells(i, "B")
Case Is < 0
sign = "负数"
Case Is > 0
sign = "正数"
Case Else
sign = "零"
End Select
Cells(i, "C") = sign '向 C 列对应单元格中写入数据
i = i + 1 '更新哨兵变量
Loop
End Sub
4、Do Until 循环和 Select Case 语句, 代码如下:
Sub sign()
Dim sign As String, i As Integer '声明变量
i = 3 '初始化循环变量
Do Until Cells(i, "B") = ""
Select Case Cells(i, "B")
Case Is < 0
sign = "负数"
Case Is > 0
sign = "正数"
Case Else
sign = "零"
End Select
Cells(i, "C") = sign
i = i + 1 '更新循环变量
Loop
End Sub
非学无以广才,非志无以成学。