1

我有很久以前编写的 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

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

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

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

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

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

4

1 回答 1

3

首先,如果您在每个分支中都有相同的代码,则不需要该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
于 2016-01-25T15:48:45.393 回答