VBScript中的循环语句(二)

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]

以下示例程序是将不规则空格分隔的数据重写成逗号分隔的有序排列的数据:
text.txt

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

运行后的结果如下:
newtext.txt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shelyer1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值