需要修改现有代码以阻止其覆盖现有文件(如果存在)

时间:2018-11-15 23:24:42

标签: excel vba

我需要修改此代码,以便首先搜索文件是否存在,如果存在,什么都不做,只显示一条消息,否则,下面的代码将自动创建文件。预先感谢。

    Option Explicit
    Public WithEvents MonitorApp As Application

    Private Sub Workbook_Open()

    Dim strGenericFilePath      As String: strGenericFilePath = "\\Server2016\Common\Register\"
    Dim strYear                 As String: strYear = Year(Date) & "\"
    Dim strMonth                As String: strMonth = MonthName(Month(Date)) & "\"
    Dim strFileName             As String: strFileName = "Register Sheet " & Format(Date, "mmm dd yyyy")

    Application.DisplayAlerts = False

    If Len(Dir(strGenericFilePath & strYear, vbDirectory)) = 0 Then
        MkDir strGenericFilePath & strYear
    End If

    If Len(Dir(strGenericFilePath & strYear & strMonth, vbDirectory)) = 0 Then
        MkDir strGenericFilePath & strYear & strMonth
    End If

    If Len(Dir(strGenericFilePath & strYear & strMonth, vbDirectory)) = 0 Then
        MkDir strGenericFilePath & strYear & strMonth
    End If

    ActiveWorkbook.SaveAs Filename:= strGenericFilePath & strYear & strMonth & strFileName, _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    Application.DisplayAlerts = True

    MsgBox "File Saved As: " & vbNewLine & strGenericFilePath & strYear & strMonth & strFileName

    End Sub

0 个答案:

没有答案