excel - 为什么这个 VBScript 在 Excel VBA 中运行良好,但作为独立的 vbscript?

标签 excel vba windows vbscript scripting

我编写了这个 VBscript 来创建一个 zip 文件,然后将一个文件夹复制到其中。当我在 excel 中将脚本作为 Sub 运行时,它会创建文件并将文件夹完美地复制到其中,但是当我将其作为 .vbs 文件运行时,它会创建 zip 文件,并且没有其他任何事情发生。我尝试在创建 zip 文件之后但在它复制文件之前添加 wscript.sleep 10000 ,但仍然没有任何 react 。我还尝试使用 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))

最佳答案

此行: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

关于excel - 为什么这个 VBScript 在 Excel VBA 中运行良好,但作为独立的 vbscript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63157293/

相关文章:

excel - 为什么这个暗淡定义错误?

windows和apache下的Python作为FastCGI

windows - Webstorm 11 中的菜单和工具栏字体大小

c - 枚举桌面上的所有窗口句柄

vba - 对于每个编译错误(多个范围)

vba - 如何从模板生成工作表

excel - 隐藏 MS Office 功能区中的加载项选项卡(尤其是 PowerPivot 选项卡)

c# - 使用 EPPlus 生成电子表格时是否可以忽略 Excel 警告?

excel - 用于在选定单元格中插入文本的按钮

VBA - 获取数组长度时限定符无效