Results 1 to 5 of 5
  1. #1
    New Lounger
    Join Date
    Apr 2016
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Rename (append) a Word file with data from bookmark/form field

    I have thousands of word documents, each containing unique customer names. The customer names are within a boomark 'name'. I have to manually copy the customer name, and append it to the filename.

    For eg, if file name is 2B101.doc, then I have to open this word document, copy the customer name at the bookmark, and apend it the file name, like this - 2B101Alex Fernandes.doc.

    Is there a way this can be automated using word vba macros, or any other prog. lang. ?

    Thank you.

  2. #2
    Super Moderator
    Join Date
    May 2002
    Location
    Canberra, Australian Capital Territory, Australia
    Posts
    5,055
    Thanks
    2
    Thanked 417 Times in 346 Posts
    Try the following macro. Simply run the macro, select folder to process and sit back while it renames all your documents.
    Code:
    Sub UpdateDocumentNames()
    Application.ScreenUpdating = False
    Dim strFolder As String, strFile As String, strDocNm As String, strTmp As String, wdDoc As Document
    Dim FSO As Object, objFile As Object
    strDocNm = ActiveDocument.FullName
    strFolder = GetFolder
    If strFolder = "" Then Exit Sub
    Set FSO = CreateObject("Scripting.FileSystemObject")
    strFile = Dir(strFolder & "\*.doc", vbNormal)
    While strFile <> ""
      If strFolder & "\" & strFile <> strDocNm Then
        Set wdDoc = Documents.Open(FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
        With wdDoc
          If .Bookmarks.Exists("Name") Then
            strTmp = .Bookmarks("Name").Range.Text
          Else
            strTmp = ""
          End If
          .Close SaveChanges:=False
        End With
      End If
      If strTmp <> "" Then
        strTmp = Replace(strFile, ".doc", strTmp & ".doc")
        Set objFile = FSO.GetFile(strFolder & "\" & strFile)
        objFile.Name = strTmp
      End If
      strFile = Dir()
    Wend
    Set wdDoc = Nothing: Set objFile = Nothing: Set FSO = Nothing
    Application.ScreenUpdating = True
    End Sub
    
    Function GetFolder() As String
    Dim oFolder As Object
    GetFolder = ""
    Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
    If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
    Set oFolder = Nothing
    End Function
    Cheers,

    Paul Edstein
    [MS MVP - Word]

  3. #3
    Super Moderator
    Join Date
    May 2002
    Location
    Canberra, Australian Capital Territory, Australia
    Posts
    5,055
    Thanks
    2
    Thanked 417 Times in 346 Posts
    Quote Originally Posted by Alan_Joseph View Post
    I know that you can use a macro that will cause Word to automatically name the document based on the title provided. The problem is that it only works when you're first saving a new document so it could help you going forward if you plan on saving similar docs. I know it can be modified, just not sure to what degree. It's called FileSaveAs..
    ...
    Don't know if you'll have any use for it but I figured I'd throw it in here anyway. Haven't come across anything that will automate existing files in this way yet but I'll do a little more searching.
    Posting code that is unrelated to the OP's question isn't at all helpful. Not only doesn't the code you posted have anything to do with retrieving bookmarked content (which the OP specified), using it requires the user to manually open every document to be processed - and then gives it a name quite unrelated to whatever name it already had.

    Finally, when posting code, please use the code tags. They're on the 'Go Advanced' tab at the bottom of this screen. Without them, your code loses much of whatever structure it had.
    Cheers,

    Paul Edstein
    [MS MVP - Word]

  4. #4
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,436
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts
    Vik1,

    Here's a PowerShell program which will accomplish what you want as I read it.

    It will read all document files *.Doc? in the specified directory.
    It will search for the bookmark called "Name" and extract the value contained therein.
    It will save the file to the Specified Destination with the name appended to the original filename.
    Note: All files will be saved in their original format. Also the Source directory should only have .doc & .docx files in it, unless you add more tests to the code to exclude other Word File types!

    Source Test Files:
    SourceFiles.PNG

    Processed Test Files:
    ProcessedDocs.PNG

    PowerShell Code: CHANGE ITEMS IN BLUE to meet your system setup!
    Code:
    $DirectoryToSaveTo='G:\Test\Documents'
    
    $Word = New-Object -ComObject Word.Application
    $Word.Visible = $false #set this to true for debugging
    
    if (!(Test-Path -path "$DirectoryToSaveTo")) {  #create it if not existing
      New-Item "$DirectoryToSaveTo" -type directory | out-null
    }
    
    $wdFormatXMLDocument=12 # http://msdn.microsoft.com/en-us/library/bb238158%28v=office.12%29.aspx
    $wdFormatDocument=0
    
    $Source = Get-ChildItem -Path "G:\Test" -Filter "*.doc?"
    
    ForEach ($Doc in $Source)   {
    
      $CurDoc = $Word.Documents.Open($Doc.Fullname)
      $FNParts = $doc.Fullname.Split('.')
      $FExt = $FNParts[1]
      $FNParts = $FNParts[0].Split('\')
      $FName = $FNParts[$FNParts.count-1]
    
      $ErrorActionPreference = "SilentlyContinue"
      $BkMk = $CurDoc.Bookmarks("Name").Range
      $ErrorActionPreference = "Continue"
    
      If (-not($BkMk.Text -eq "")) {
    
        If ($FExt -eq "Doc") { 
          $wdSaveFmt = $wdFormatDocument
        }
        Else {
          $wdSaveFmt = $wdFormatXMLDocument
        }
    
        Write-Host "$($doc.fullname) - $($BkMk.Text)"
      
        $filename = "$DirectoryToSaveTo\" + "$FName$($BKMk.Text)" + ".$FExt"
      
        if (test-path $filename) { 
          Remove-Item $filename -Force  #delete the file if it already exists
        }
      
        $CurDoc.SaveAs([ref]$filename, [ref]$wdSaveFmt)
        $CurDoc.Close() #close the document
    
      } #End If (-not($BkMk...
      Else {
          Write-Host "$($doc.fullname) - BookMark Not Found! No Action Taken)"
      }
    
    } #End ForEach ($Doc...
    
    $Word.Quit() #and the instance of Word
    HTH
    Last edited by RetiredGeek; 2016-06-15 at 22:20.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  5. #5
    New Lounger
    Join Date
    Apr 2016
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you Sir. Will try it out.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •