【问题标题】:Delete If Present at Destination, Copy To Destination If Error Move to Next如果目标存在则删除,如果错误则复制到目标移动到下一个
【发布时间】:2016-01-25 15:18:39
【问题描述】:

我有很久以前编写的 VBScript,用于根据文件名识别 PDF。然后它将数据附加到文件名并将其移动到正确的目录。我将其作为Select Case 进行,以便它循环许多文件名。我现在正在尝试修改脚本以检查具有新名称的文件是否已经在目标目录中,如果是,则删除旧文件并复制新文件(如果文件已打开且无法覆盖,忽略并移至下一个)。我一直在许多论坛上搜索,并且能够找到我正在尝试的部分,但无法成功地将这些流程集成到我的脚本中。这是我的选择案例,这部分是随着“VariableAddedtoFileName”的变化而重复的。

Select Case Pname
    Case "FileName"
        sDestinationFolder = "\\Server\FileDir\"       
        sDestinationName = "VariableAddedtoFileName"      
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        sSourceFile = objStartFolder & "\" & objFile.Name
        sDestinationFile = sDestinationFolder & "\" & Pname & " " & _
            sDestinationName & Right(objFile.Name, 4)

        If oFSO.FileExists(sDestinationFile) Then
            Set oFSO = Nothing
        Else
            oFSO.MoveFile sSourceFile, sDestinationFile
            Set oFSO = Nothing
        End If
    Case "StatementScriptTest"
    Case Else
End Select

因此,如果我将If oFSO.FileExists 组中的Set oFSO 行更改为oFSO.DeleteFile sDestinationFile,它会删除文件,但不会复制新文件。如果重新运行,它会复制该文件,因为它不再存在。我尝试了多种尝试操纵if 语句和then 的组合,但没有成功。我还尝试删除 if 部分之前的文件,但无济于事。任何帮助将不胜感激。

如果需要我可以提供的完整脚本,我只列出了这一部分,因为它是多次重新运行的部分。我也知道有多个类似的帖子,但我想弄清楚如何更新我的代码才能工作。

更新:我已经使用CopyFile修复了覆盖:

 If oFSO.FileExists(sDestinationFile) Then
    oFSO.CopyFile sSourceFile, sDestinationFile, True
Else
    oFSO.CopyFile sSourceFile, sDestinationFile, True
    Set oFSO = Nothing
End If

但如果在尝试覆盖时文件处于打开状态,我仍然会收到错误消息。

【问题讨论】:

    标签: vbscript fso


    【解决方案1】:

    首先,如果您在每个分支中都有相同的代码,则不需要IF 语句。只需使用oFSO.CopyFile sSourceFile, sDestinationFile, True,它就会为您完成工作。

    其次,为了捕捉错误,您必须在复制命令之前使用On Error Resume Next 声明并检查是否触发了一些错误:

    On Error Resume Next ' this tells VB to not throw errors and to populate the Err object when an error occurs
    
    oFSO.CopyFile sSourceFile, sDestinationFile, True
    
    IF Err.Number <> 0 Then
        ' do something when error occurs
        ' ...
    
        Err.Clear ' clears the error so it will not trigger this on the loop if no more errors occur
    End IF
    
    ' When you want to stop ignoring the errors
    On Error GoTo 0
    

    【讨论】:

    • 太棒了rcdmk!看来我把事情复杂化了。是时候再喝杯咖啡了……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2010-12-04
    • 1970-01-01
    • 2016-01-23
    相关资源
    最近更新 更多