全民一起VBA基础篇第六课:While语句和多重循环

while语句

while cells(i,2) <> “”
可用来检查内容是否为空,来标记是否到尾巴了

Sub highlightquick()
Dim i As Integer
i = 2
While Cells(i, 2) <> "" '判断是否为空
    If Cells(i, 2) > 500 Then '判断单元格的数值
    
        Cells(i, 2).Font.Bold = True    '用来加粗
        
        With Cells(i, 2).Font   '用来改字体颜色
            .Color = -16776961
            .TintAndShade = 0
        End With
        
    End If
    
    i = i + 1

Wend    '和开头的while呼应

End Sub

同样完成和上一篇一样的任务,这次用while循环
这里解决的是没有空行的情况,有空行的情况之后再谈
如果要判断一行中任一列不为空就执行,可以改为

While Cells(i, 2) <> "" or Cells(i, 3) <> "" 

实际编程中用do while 更多
Sub highlightquick()
Dim i As Integer
i = 2
Do While Cells(i, 2) <> “” '判断是否为空
If Cells(i, 2) > 500 Then '判断单元格的数值

    Cells(i, 2).Font.Bold = True    '用来加粗
    
    With Cells(i, 2).Font   '用来改字体颜色
        .Color = -16776961
        .TintAndShade = 0
    End With
    
End If

i = i + 1
Loop    '和开头的while呼应
End Sub

求平均值

Option Explicit
Sub average()
Dim total
Dim count
Dim mean
Dim i
i = 2
total = 0
count = 0
Do While Cells(i, 2) <> ""  '判断是否为空
    total = total + Cells(i, 2) '求和器
    count = count + 1 '计数器
    mean = total / count '算均值
    i = i + 1
Loop

Cells(4, 4) = mean

End Sub

双重循环

对二重表格进行运算

Option Explicit
Sub toKG()

Dim i, j

i = 2

If Cells(7, 9) = "磅" Then '判断是否能进行转换

    Do While Cells(i, 1) <> "" '控制行
    
        For j = 2 To 10 Step 1 '控制列
        
        Cells(i, j) = Cells(i, j) / 0.45
        
        Next j
        
    i = i + 1
    
        Loop
        
        Cells(7, 9) = "千克"
End If

End Sub

发布了26 篇原创文章 · 获赞 5 · 访问量 1105

猜你喜欢

转载自blog.csdn.net/qq_43568982/article/details/103749870
今日推荐