Search code examples
vbams-wordoverwritesave-as

Word - Prevent SaveAs2 (VBA) from overwriting


Somewhere on the internet I found this code to easily save a .docx file out of a .dotx file into the desired folder:

Sub SaveFileInTheCorrectDirectory()
    ActiveDocument.SaveAs2 "[the correct directory, put in manually by me in the VBA code]" & InputBox("Type the desired file name", "Save As")
End Sub

However, this code automatically overwrites an already existing file with the same name (and in the same directory, of course). I've tried looking for code to fix this, and found a few suggestions:

But I can't figure out how to implement them...

Could someone be so kind to assist me?

Thanks!

PS Is there added value to use "SaveAs2" instead of "SaveAs" or the other way around?


Solution

  • That's as simple as:

    Dim StrName as String
    StrName = InputBox("Type the desired file name", "Save As")
    If Trim(StrName) = "" then Exit Sub
    If Dir(StrPath & StrName & ".docx") = "" Then ActiveDocument.SaveAs2 StrPath & StrName & ".docx"
    

    where StrPath & StrName are the path & name, respectively.

    Note: I haven't added any code for what to do if the file exists because you haven't said what you want to do in that case. Post a new question if you need help with that.