VBA中For…Next与 Foreach函数都是循环的作用,区别是For…Next主要针对变量做循环,而Foreach针对对象本身去做循环。
具体需求
需要把表格中各科成绩大于等于80分的成绩标出来(主要是格式更改),字体倾斜、颜色更改为红色,底色标注青绿色。
语法规则/For…Next
For 循环变量=初值 to 终值 step步长
循环体1
[exit for]
循环体2
next 循环变量
代码解析
'循环改变字体格式和底色(>=80分)
Subscore1()
Dimi, j%
Fori = 2 To Sheets(1).Range('a10000').End(xlUp).Row
For j = 3 ToSheets(1).Range('aa1').End(xlToLeft).Column
If Cells(i, j).Value >= 80 Then
Cells(i, j).Font.ColorIndex = 3
Cells(i, j).Font.Italic = True
Cells(i,j).Interior.ColorIndex = 8
End If
Next
Next
EndSub
=============================
语法规则/ Foreach
For Each元素变量 In对象集合或数组名称
语句块1
[Exit For]
语句块2
Next元素变量
代码解析
'循环改变字体格式和底色(>=80分)
Subscore2()
Dimrng As Range
ForEach rng In Sheets(1).Range('C2:E11')
If rng.Value >= 80 Then
rng.Font.ColorIndex = 3
rng.Font.Italic = True
rng.Interior.ColorIndex = 8
End If
Next
EndSub
执行结果
文章来源:原创文章
联系客服