【问题标题】:Why does this VBScript run fine in Excel VBA but as a stand alone vbscript?为什么这个 VBScript 在 Excel VBA 中运行良好,但作为独立的 vbscript?
【发布时间】:2020-11-19 06:16:42
【问题描述】:

我编写了这个 VBscript 来创建一个 zip 文件,然后将一个文件夹复制到其中。当我在 excel 中将脚本作为 Sub 运行时,它会创建文件并将文件夹完美地复制到其中,但是当我将其作为 .vbs 文件运行时,它会创建 zip 文件,并且没有其他任何事情发生。我尝试在创建 zip 文件之后但在它复制文件之前添加 wscript.sleep 10000 ,但仍然没有任何反应。我还尝试使用 FileExists 检查 zip 文件在复制之前是否存在,它返回 true 但仍然不会复制。这是代码。

Dim dtmValu
dtmValue = Now()
Dim DestPath
DestPath = "C:\Users\FirstUser\Desktop\Test\" & Month(dtmValue) & "_" & Day(dtmValue) & "_" & Year(dtmValue) & ".zip"
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(DestPath, 8, vbTrue)
BlankZip = "PK" & Chr(5) & Chr(6)
For x = 0 To 17
BlankZip = BlankZip & Chr(0)
Next
ts.Write BlankZip
        Set objFolder = Nothing
        Set objShell = Nothing
Set fso = Nothing
Set ts = Nothing
 
 
Set objShell = CreateObject("shell.Application")
Set oFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objShell.Namespace(DestPath)
Dim sFolder
sFolder = "C:\Users\FirstUser\Desktop\TestSource\"
objFolder.CopyHere (oFso.GetAbsolutePathName(sFolder))

【问题讨论】:

  • 我的意思是,聪明的答案是 vba vbscript
  • 不确定它是否能解决问题,但我猜你不需要最后一行中的额外括号:objFolder.CopyHere oFso.GetAbsolutePathName(sFolder)
  • 我尝试删除多余的括号,但没有任何变化。

标签: excel vba windows vbscript scripting


【解决方案1】:

这一行:objFolder.CopyHere (oFso.GetAbsolutePathName(sFolder)) 执行异步,大概你的objFolder 在完成操作之前就被销毁了。

在退出脚本之前尝试添加一些逻辑来检查复制是否完成。您提到您添加了等待,但很难说这是否足够长,并且许多因素可能会使时间有所不同。但是这种方法应该更稳定一些。在复制之前对项目进行计数,然后比较之后的计数,并且在复制完成之前不要让它结束:

'// your pre-copy code here:
'//...

Set objShell = CreateObject("shell.Application")
Set oFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objShell.Namespace(DestPath)
cnt = objFolder.Items.Count + 1 '// I added this
Dim sFolder

objFolder.CopyHere oFso.GetAbsolutePathName(sFolder) 

'// and this
While objFolder.Items.Count < cnt
    WScript.Sleep 100
Wend

【讨论】:

  • 感谢这工作。由于它运行良好的 VBA,我猜想在 VBA 编辑器中完成时,copyhere 方法不会异步执行?
猜你喜欢
  • 1970-01-01
  • 2020-06-04
  • 1970-01-01
  • 2021-03-13
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多