第二组VB脚本比第一组语句先运行

时间:2018-12-12 07:53:00

标签: vba

我有两套VB脚本,一套是创建文件,第二套是重命名文件。

当我运行它时,它给我错误:“找不到文件,在移动命令时出现错误行”,这意味着它正在寻找要重命名的文件。但是我想生成一个文件然后重命名。

当我单独跑步时,它工作正常。有人可以协助解决问题吗?

设置1:

' it will create a object called Export.tar.gz  (Working fine - Due to security contrarian i have partially placed the code in set1)

Dim objShell
Set objShell = WScript.CreateObject ("WScript.shell")

objShell.run "cmd /C CD D:\test\VB practice\Mrcctl ************************************ localfolder=D:\FullExport"
Set objShell = Nothing

Set2:

Dim ObjFSO
SET ObjFSO = CreateObject("Scripting.FileSystemObject")
Dim file1, file2

file1 = "D:\FullExport\Export.tar.gz"
file2 = "D:\FullExport\Export" & year(date) & month(date) & Day(Date) & ".tar.gz"

ObjFSO.MoveFile file1, file2

Set ObjFSO = Nothing

1 个答案:

答案 0 :(得分:0)

shell命令在单独的系统线程中运行,因此,shell完成后,VBS脚本将不会等待。要解决此问题,您需要等到文件由系统实际创建和释放后再重命名。 作为一种可能的解决方案,您可以如下更新第二个脚本:

Set2

Dim ObjFSO
SET ObjFSO = CreateObject("Scripting.FileSystemObject")
Dim file1, file2

file1 = "D:\FullExport\Export.tar.gz"
file2 = "D:\FullExport\Export" & year(date) & month(date) & Day(Date) & ".tar.gz"

On Error Resume Next
Do
    Err.Clear
    Set oFile = ObjFSO.OpenTextFile(file1, 8, False)
    if err.number = 0 then Exit Do

    WScript.Sleep 1000
Loop

On Error Goto 0
oFile.Close
set oFile = Nothing

ObjFSO.MoveFile file1, file2

Set ObjFSO = Nothing