如果文件存在,则另存为时间戳记

时间:2018-08-29 09:53:50

标签: excel excel-vba

我正在尝试使以下内容在我的代码中起作用。我是宏来保存该文件,如果该文件已经存在,则将其另存为时间戳。我有以下内容,但它在“ ActiveWorkbook.SaveAs(FPath和“ \”&FName和Format(DateTime.Now,“ yyyy-MM-dd hh:mm:ss”)&“ xlsx”)”处停止做错了吗?

'~~> Save the file

Dim TestStr As String

TestStr = ""

On Error Resume Next
TestStr = Dir(FPath & "\" & FName & ".xlsx")

On Error GoTo 0
If TestStr = "" Then
MsgBox "New file name: " & FName & ".xlsx"
ActiveWorkbook.SaveAs filename:=FPath & "\" & FName & ".xlsx", FileFormat:=51
Workbooks(FName & ".xlsx").Close

'~~> Mark as saved
Workbooks("Sample.xlsm").Worksheets("Front Page").Cells(Application.Match("Vendor", Worksheets("Front Page").Range("A1:A42"), 0), 3).Value = "OK"

Else
MsgBox "File " & FName & ".xslx" & " already exist." & vbCrLf & "New vesion saved with timestamp."
ActiveWorkbook.SaveAs (FPath & "\" & FName & Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss") & "xlsx")
Workbooks(FName & Format(Now(), "yyyy-MM-dd hh:mm:ss") & ".xlsx").Close

End If

Exit Sub

1 个答案:

答案 0 :(得分:0)

文件名中不能包含:,而且在“ xlsx ”之前还缺少句号Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss") & "xlsx"),因此以下内容将达到您的期望:

Dim TestStr As String

TestStr = ""

On Error Resume Next
TestStr = Dir(FPath & "\" & FName & ".xlsx")

On Error GoTo 0
If TestStr = "" Then
    MsgBox "New file name: " & FName & ".xlsx"
    ActiveWorkbook.SaveAs Filename:=FPath & "\" & FName & ".xlsx", FileFormat:=51
    Workbooks(FName & ".xlsx").Close

    '~~> Mark as saved
    Workbooks("Sample.xlsm").Worksheets("Front Page").Cells(Application.Match("Vendor", Worksheets("Front Page").Range("A1:A42"), 0), 3).Value = "OK"
Else
    MsgBox "File " & FName & ".xslx" & " already exist." & vbCrLf & "New vesion saved with timestamp."
    ActiveWorkbook.SaveAs (FPath & "\" & FName & Format(DateTime.Now, "yyyy-MM-dd hh-mm-ss") & ".xlsx")
    Workbooks(FName & Format(Now(), "yyyy-MM-dd hh-mm-ss") & ".xlsx").Close
End If

Exit Sub