刚开始学VBS,很多东西都还不明白。
如何根据条件来决定for语句的循环次数?比如说当条件为A时,执行“for i=0 to 50”,当条件为B时执行“for i=0 to 100”? | rem 这是一段错误的代码 | | dim asdf(2) | | asdf(0)="111111111" | | asdf(1)="222222222" | | asdf(2)="333333333" | | | | a=1 | | if a=1 then | | for i=0 to 1 | | else | | for i=0 to 2 | | end if | | s=s&asdf(i)&" " | | next | | msgbox sCOPY |
上面那段代码是错误的,但是就是我想达到的效果。
下面是我想完成的任务:
我准备用VBS给若干程序创建快捷方式,所有程序的快捷方式将会创建到开始菜单的某个文件夹,但是其中部分程序的快捷方式会创建到快速启动栏。
“程序”、“起始位置”、“图标”、等参数我用的是一维数组,快捷方式的“目标位置”我定义了一个二维数组,分别指向开始菜单和快速启动栏。
以下这段代码(从完整代码中提取的部分内容并稍做修改)可以完成任务,但是有缺陷: | | | | | | | | | | | | | | | | | dim Dir(32),Name(147),Goal(147,1),Prog(147),PPth(147),Icon(147),Parm(147),Dscp(147) | | dim a,f,g,i,j,fso,AppBox | | Set a = WScript.CreateObject("WScript.Shell") | | f = a.SpecialFolders("AllUsersStartMenu") & "\工具箱" | | | | Dir(0) = f | | Dir(04) = f & "\备份" | | Dir(05) = f & "\编辑" | | | | Set fso = Createobject("Scripting.Filesystemobject") | | | | for g=0 to 32 | | if not fso.folderexists(Dir(g)) then | | fso.createfolder(Dir(g)) | | end if | | next | | | | AppBox = "C:\Programs\" | | | | Name(0) = "MyBackup" | | Goal(0,0) = Dir(04) | | Prog(0) = "MyBackup.bat" | | PPth(0) = AppBox & "MyTools\MyBackup" | | | | Name(1) = "GVim" | | Goal(1,0) = Dir(05) | | Prog(1) = "gvim.exe" | | PPth(1) = AppBox & "Vim" | | Icon(1) = AppBox & "VMware\VMware.exe" | | | | Name(2) = "HtmlDocEdit" | | Goal(2,0) = Dir(05) | | Prog(2) = "HtmlDocEdit.exe" | | PPth(2) = AppBox & "NirSoft\HtmlDocEdit" | | Parm(2) = "/prefetch:1" | | | | Name(3) = "MadEdit" | | Goal(3,0) = Dir(05) | | Goal(3,1) = a.SpecialFolders("appdata") & "\Microsoft\Internet Explorer\Quick Launch" | | Prog(3) = "MadEdit.exe" | | PPth(3) = AppBox & "MadEdit" | | | | Name(4) = "Notepad2" | | Goal(4,0) = Dir(05) | | Prog(4) = "Notepad2.exe" | | PPth(4) = AppBox & "Notepad2" | | | | for i=0 to 4 | | for j=0 to 1 | | set link = a.CreateShortcut(Goal(i,j) & "\" & Name(i) & ".lnk") | | link.TargetPath = PPth(i) & "\" & Prog(i) | | link.WorkingDirectory = ppth(i) | | if not isempty(Icon(i)) then | | link.IconLocation = Icon(i) | | elseif not isempty(Parm(i)) then | | link.Arguments = Parm(i) | | elseif not isempty(Dscp(i)) then | | link.Description = Dscp(i) | | end if | | link.save | | next | | nextCOPY |
这段代码的确可以完成任务,但是缺陷有二:
1、多循环了一次,降低了效率。
2、仅仅是因为VBS创建快捷方式没找到参数时,不会报错,才完成的任务。
所以,我想把 | for i=0 to 4 | | for j=0 to 1COPY |
改成类似这样的语句: | for i=0 to 4 | | if isempty(goal(i,1)) then | | for j=0 to 0 | | else | | for j= 0 to 1 | | end ifCOPY |
但是这段代码又是错误的。 |