none
Date in Save As name - Bad File Name Error RRS feed

  • Question

  • I'm trying to adapt code that I found here so that my word file is saved with the Date before the file name in a yyyy-mm-dd format.

    Here is my adapted code:

    Sub FileSave()
    Dim doc As Word.Document
    
    Set doc = ActiveDocument
    If doc.Saved = False And _
    Left(doc.Name, Len("Document")) = "Document" Then
    SaveFileWithDate
    Else
    doc.Save
    End If
    End Sub
    
    Sub FileSaveAs()
    SaveFileWithDate
    End Sub
    
    
    Sub SaveFileWithDate()
    Dim s As String
    Dim sD As String
    Dim Fin As String
    
    
    With Dialogs(wdDialogFileSaveAs)
    If .Display <> 0 Then
    s = .Name
    s = Replace(s, ".doc", "")
    s = Replace(s, ".docx", "")
    sD = Format(Date, "yyyy-mm-dd")
    Fin = sD & " - " & s
    
    ActiveDocument.SaveAs Fin
    End If
    End With
    End Sub

    Whenever I try to save documents created based upon this template I get a VB error that it is not a valid file name.

    My first question is: what have I done wrong?

    My second question is: is there a better way to do this?

    Thanks for your help.

    Friday, December 9, 2011 4:27 PM

Answers

  • hmmm. Not sure why it's not working for me.

     

    The replacements were leftover from when the date was added to the end of the filename. If the file type was not removed the date would have been after .docx or .doc. I also didn't want to lock the user into saving as a specific file type through ActiveDocument.SaveAs ,,

    But you're right; they're not needed when the date is put up front.

    Edit: I figured it out... It was a conflict created by another line of code. Thanks for your help.

     


    • Edited by bryangarner Friday, December 9, 2011 5:57 PM
    • Marked as answer by bryangarner Friday, December 9, 2011 5:57 PM
    Friday, December 9, 2011 5:56 PM

All replies

  • The code works for me, but you should place the line

    s = Replace(s, ".docx", "")

    before the line

    s = Replace(s, ".doc", "")

    otherwise, if the user specifies a name with extension .docx, .doc will be removed and the x will remain.

    But why do you want to remove the extension at all?


    Regards, Hans Vogelaar
    Friday, December 9, 2011 4:41 PM
  • hmmm. Not sure why it's not working for me.

     

    The replacements were leftover from when the date was added to the end of the filename. If the file type was not removed the date would have been after .docx or .doc. I also didn't want to lock the user into saving as a specific file type through ActiveDocument.SaveAs ,,

    But you're right; they're not needed when the date is put up front.

    Edit: I figured it out... It was a conflict created by another line of code. Thanks for your help.

     


    • Edited by bryangarner Friday, December 9, 2011 5:57 PM
    • Marked as answer by bryangarner Friday, December 9, 2011 5:57 PM
    Friday, December 9, 2011 5:56 PM