3、For…Next
以指定次数重复执行一组语句。在一般循环语句使用较多。
语句结构如下:
For counte r= start To end [Step step]
[statements]
[Exit For]
[statements]
Next
For example:
计算1至100的总和
dim total
total=0
for i=1 to 100
total=total+i
next
msgbox("1到" & i-1 & "的总和是:" & total )
4、For Each…Next
对数组或集合中的每个元素重复执行一组语句。在数据处理中应用较多。
语句结构如下:
For Each element In group
[statements]
[Exit For]
[statements]
Next [element]
以下示例程序是将不规则空格分隔的数据重写成逗号分隔的有序排列的数据:
Sub OnClick()
dim fso,myfile,mytext
const ForReading=1
set fso=createobject("scripting.filesystemobject")
set myfile=fso.opentextfile("C:\Users\shelyer\Desktop\111\test.txt",ForReading)
mytext=myfile.readall
dim outfile,newt
stext=split(mytext,vbcrlf) '对每行进行分割
'新建newfile.txt文件,并写入test.txt中的内容
set outfile=fso.createtextfile("C:\Users\shelyer\Desktop\111\newtest.txt")
dim i,stext
for each i in stext '对每一项进行循环
newt=split(newtext(i),space(1)) '按空格进行分割
outfile.writeline(newt(0)&","&newt(1)&","&newt(2)&","&newt(3))
next
End Sub
'将不规则空格调整为单个空格间隔
function newtext(txt)
dim r
r=replace(txt,space(2),space(1))
do
m=len(r)
r=replace(r,space(2),space(1))
n=len(r)
loop until m=n
newtext=r
end function
运行后的结果如下: