全民一起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

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值