Radish
Radish

Reputation: 11

Macro coding, how to automate renaming a document to the above folders name

I want Word VBA macro to rename the document to the folder it lives in.

Sub SaveAsDOCX()
'
OpenDocName = ActiveDocument.FullName
lengthFileName `enter code here`= Len(OpenDocName)
OpenDocName = Left(OpenDocName, lengthFileName - 4)
'
ChangeFileOpenDirectory (ActiveDocument.Path & "\")
ActiveDocument.SaveAs2 FileName:=(OpenDocName & ".docx"), 
FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", 
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, 
EmbedTrueTypeFonts:=False, SaveFormsData:=False, 
SaveAsAOCELetter:=False, CompatibilityMode:=0
ActiveWindow.Close
End Sub

Right now the code functions to rename the DOCX as the old file name, but I want to extract from the directory the folders name, and rename the document that. Unfortunately I need this macro to run in a lot of different folders so I need it to stay dynamic, and can't use explicit folder paths.

Upvotes: 0

Views: 377

Answers (2)

Radish
Radish

Reputation: 11

Actually pretty simple. Used the ActiveDocument to get the path string, split it, ubound to the top, -1 to locate the parent folders name in the array, and then called that resulting string. The ending code looks like:

Dim name, nameSplit, ParentFolderName
OpenDocName = ActiveDocument.FullName
nameSplit = Split(OpenDocName, "\")
ParentFolderName = (UBound(nameSplit) - 1)

and then when performing SaveAs2 call the following as the FileName:=

(nameSplit(ParentFolderName) & ".docx") 

Upvotes: 1

Ronan Vico
Ronan Vico

Reputation: 605

'That line gets the Full path to the Folder where the document is located.

 ThisDocument.path

'That line get the FullPath to the Document place

ThisDocument.FullName

Example one , you can create a new string for the name document

 dim docpath as string
 Dim docname As String
docname = VBA.Split(VBA.Mid(ActiveDocument.FullName, VBA.InStrRev(ActiveDocument.FullName, "\") + 1), ".")(0)
DocPath = ThisDocument.Path & "\" & docname &  ".docx"

Example 2

dim docpath as string
 Dim docname As String
docname = Vba.Split(ActiveDocument,".")(0)
DocPath = ThisDocument.Path & "\" & docname &  ".docx"

I do not know if is that you want , please , comment below if that helped you , i want to help you!

Upvotes: 1

Related Questions