我希望Word VBA宏将文档重命名为它所在的文件夹。
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
现在代码的功能是将DOCX重命名为旧文件名,但我想从目录中提取文件夹名称,并重命名该文件。不幸的是我需要这个宏在很多不同的文件夹中运行所以我需要它保持动态,并且不能使用显式文件夹路径。
'该行获取文档所在文件夹的完整路径。
ThisDocument.path
'该行获取文档位置的完整路径
ThisDocument.FullName
例如,您可以为名称文档创建一个新字符串
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"
例2
dim docpath as string
Dim docname As String
docname = Vba.Split(ActiveDocument,".")(0)
DocPath = ThisDocument.Path & "\" & docname & ".docx"
我不知道你是否想要,请在下面发表评论,如果这对你有所帮助,我想帮助你!
其实很简单。使用ActiveDocument获取路径字符串,将其拆分,ubound到顶部,-1以在数组中找到父文件夹名称,然后调用该结果字符串。结尾代码如下:
Dim name, nameSplit, ParentFolderName
OpenDocName = ActiveDocument.FullName
nameSplit = Split(OpenDocName, "\")
ParentFolderName = (UBound(nameSplit) - 1)
然后在执行SaveAs2时,将以下内容称为FileName:=
(nameSplit(ParentFolderName) & ".docx")