PDA

View Full Version : VBA code to name a document



JamesbUk
09-17-2023, 01:18 PM
Hello,

I have a macro for saving a word document to a specific folder and it works great. The only problem is that i dont know how to name the document correctly. the code is below.


Sub SaveAFile()
Dim path As String
path = "C:\Users\User\Test.docx"
With ActiveDocument
.SaveAs FileName:=path
.Close
End With
End Sub

with this code the document is named Test.docx when its saved to the new folder. I want the document to keep its current name. Can anyone help please.

June7
09-17-2023, 02:12 PM
Build a path string.

I don't see code that creates a new folder. I only see a hard-coded path string.

Try retrieving document name with ActiveDocument.Name

JamesbUk
09-17-2023, 02:32 PM
Thanks, so I replaced =path with ActiveDocument.Name but now the document doesn’t go to the location I want. I’m not sure where it went.

June7
09-17-2023, 04:06 PM
You need to build a full path string.

path = "some folder path\" & ActiveDocument.Name

Where do you want folder path to come from - user input?

JamesbUk
09-17-2023, 04:32 PM
So the word document will be open and it will be in my documents folder.The document will have a different name every time. The macro will then save it in "C:\Users\User\Test.docx". at the moment the macro is saving it to "C:\Users\User\Test.docx" but it is naming the document Test.

JamesbUk
09-17-2023, 04:42 PM
I don’t want the code to create a new folder. I want the word document to go to an existing folder which in this example is "C:\Users\User\Test.docx"

JamesbUk
09-17-2023, 04:58 PM
At the moment the macro is sending the document to the correct folder "C:\Users\User\Test.docx" but it is renaming the document test. I want the document to keep its original name

gmaxey
09-17-2023, 05:21 PM
Sub SaveAFile()
Dim path As String
path = "C:\Users\User" & ActiveDocument.Name
With ActiveDocument
.SaveAs FileName:=path
.Close
End With
End Sub

June7
09-17-2023, 05:43 PM
Don't forget \ before file name. If you don't post code between CODE tags, forum drops that \ character unless you go to Advanced edit and unclick "Automatically parse links in text".


You have a folder named "User"?

JamesbUk
09-17-2023, 06:02 PM
That’s worked pretty well thank you