【问题标题】:Rename (append) word file based on a bookmark using Word VBA Macros使用 Word VBA 宏基于书签重命名(附加)word 文件
【发布时间】:2016-06-16 16:09:51
【问题描述】:

使用 Word VBA 宏,我可以重命名(附加)一个包含在书签中的值的 .doc 文件吗?

例如,我有一个书签“名称”存在于文件夹“源”中的数千个文档中。每个文件在书签中都有不同的值,例如 Richard、Alex、William 等。

如果我的文件是“123.doc”,其中包含值为“Richard”的书签“name” 那么我想把word文件重命名为“123Richard.doc”

如果 456.doc,再次包含相同的书签“名称”和值“亚历克斯”, 然后我希望将单词 file 重命名为“456Alex.doc”

我只想使用单词 VBA 宏。

谢谢。

【问题讨论】:

  • 请有任何建议。

标签: vba ms-word


【解决方案1】:

要重命名单个文档,您可以使用:

Public Sub updateName()
    Dim name As String

    If ActiveDocument.Bookmarks.Exists("BookMarkName") Then
        'extract the name from the bookmark
        name = ActiveDocument.Bookmarks("BookmarkName").Range.Text

        'Save the doc with the new name
        ActiveDocument.SaveAs _
               Left(ActiveDocument.FullName, Len(ActiveDocument.FullName) - 4) & _
               name & Right(ActiveDocument.FullName, 4)

    End If

End Sub

要在特定子文件夹中的所有文档中执行此操作,您可以使用遍历宏,请查看 VBA express 中的此代码:http://www.vbaexpress.com/kb/getarticle.php?kb_id=76

它将打开特定文件夹及其所有子文件夹中的所有文件。只需在循环内添加对 updateName 的调用:

If Right(strName, 4) = ".doc" Or Right(strName, 4) = ".dot" Then 
            Set wdDoc = Documents.Open(FileName:=strPath & "\" & strName, _ 
            ReadOnly:=False, Format:=wdOpenFormatAuto) 

            'Call the macro that performs work on the file pasing a reference to it

            'change the name of the open document
            changeDoc 

             'we close saving changes
            wdDoc.Close wdSaveChanges 
End If

更新:

根据两个书签中的值重命名文档:

Public Sub updateName2()
    Dim firstName, lastName As String

    'make sure the bookmarks exist
    If ActiveDocument.Bookmarks.Exists("FNAME") And _
        ActiveDocument.Bookmarks.Exists("LNAME") Then

        'extract the names
        firstName = ActiveDocument.Bookmarks("FNAME").Range.Text
        lastName = ActiveDocument.Bookmarks("LNAME").Range.Text

        'save the document with the new name
         ActiveDocument.SaveAs _
             ActiveDocument.path & "\" & firstName & _
             " " & lastName & ActiveDocument.name
    End If

End Sub

【讨论】:

  • 很高兴听到!您能否将问题标记为已解决?
  • @boogiehound 您可能想再次发表评论并“标记”vicki(在姓名前加一个 & 号)以确保她在收件箱中收到通知。
  • @vicki 能否将问题标记为已解决?
  • @Cindy 感谢您的信息!
  • Dim name As String Dim path As String '从书签中提取名称 name = ActiveDocument.Bookmarks("FNAME").Range.Text name2 = ActiveDocument.Bookmarks("LNAME").Range. Text '用新名称保存文档 ActiveDocument.SaveAs _ Left(ActiveDocument.FullName, Len(ActiveDocument.FullName) - 4) & _ name2 & "_" & name & Right(ActiveDocument.FullName, 4)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
相关资源
最近更新 更多