Search code examples
excelvba

Save file without prompts or overwriting other files


I used this to get as far as I could, but it doesn't seem to fit my case well. VBA: Saving without overwriting existing files

What I'd like to do is save an initial file without a number associated with it, and any others that try to overwrite it with (1), (2), etc. I also want this to be hands off, so if the file exists, I don't want the prompt to overwrite to appear, I'd just like it to decline and try to save as one of the next file names with the increasing numbers. I am only using this on a single sheet in a workbook

Dim wsDemo As Worksheet, i As Long, fName As String
Dim Savedir as String, curBook as String
Savedir = "C:\Users\Dio\Documents\Working Files\"
curBook = CreateObject("Scripting.FileSystemObject").GetBaseName(ActiveWorkbook.Name)
Set wsDemo = Workbooks(curBook & ".xlsx").Worksheets("Demo")

fName = "Popcorn"

    For i = 1 To 9
        If Len(Dir(Savedir & fName & " Demo " & "(" & i & ")" & Format(Date, "mm-dd-yyyy") & ".csv")) = 0 Then
            If Len(Dir(Savedir & fName & " Demo " & Format(Date, "mm-dd-yyyy") & ".csv")) = 0 Then
                wsDemo.SaveAs Savedir & fName & " Demo " & Format(Date, "mm-dd-yyyy"), 23
                Exit For
            Else
                wsDemo.SaveAs Savedir & fName & " Demo " & "(" & i & ") " & Format(Date, "mm-dd-yyyy"), 23
                Exit For
            End If
        End If
    Next i

Solution

  • If I got you right then you probably want this

    Option Explicit
    
    Sub saveAsSequence()
        Dim wsDemo As Worksheet, i As Long, fName As String
        Dim Savedir As String, curBook As String
        Savedir = "C:\Users\Dio\Documents\Working Files\"
        curBook = CreateObject("Scripting.FileSystemObject").GetBaseName(ActiveWorkbook.Name)
        Set wsDemo = Workbooks(curBook & ".xlsx").Worksheets("Demo")
        
        fName = "Popcorn"
        
        Dim filename As String
        filename = Savedir & fName & " Demo " & Format(Date, "mm-dd-yyyy") & ".csv"
            
        Do
            If FileExists(filename) Then
                i = i + 1
                filename = Savedir & fName & " Demo " & "(" & i & ") " & Format(Date, "mm-dd-yyyy") & ".csv"
            Else
                wsDemo.SaveAs filename, 23
                Exit Do
            End If
            
        Loop Until i > 1000 ' "Safe" Exit not to create an endless loop
        
    End Sub
    
    
    Function FileExists(ByVal file As String) As Boolean
        On Error Resume Next
        FileExists = False
        FileExists = Dir(file) <> ""
    End Function