How do I Truncate Filename Word 2010?

I would like to write a macro that will add a document name to our documents (not in a footer).  Our document names (from our document management system [DM]) look like this:  DOCS-#585185-v1-GENERAL_FORMS___Audit_Letter.docx.  All I really need is 585185-v1.

VB is very new to me and I'm anxious to learn more.

(Windows 7, Word 2010, sp1)
MariaJoyalAsked:
Who is Participating?
 
GrahamSkanConnect With a Mentor RetiredCommented:
OK, try this:
Sub InsertID()
    Dim strFileName As String
    Dim strID As String
    
    strFileName = ActiveDocument.Name 'e.g. "DOCS-#585185-v1-GENERAL_FORMS___Audit_Letter.docx."
    strID = Mid(strFileName, 7, 9)
    SElection.Text = strID
End Sub

Open in new window

0
 
GrahamSkanRetiredCommented:
It does depend on how consistent the pattern is, but this should do it:
Sub InsertID()
    Dim strFileName As String
    Dim strID As String
    
    strFileName = ActiveDocument.Name 'e.g. "DOCS-#585185-v1-GENERAL_FORMS___Audit_Letter.docx."
    strID = Mid(strFileName, 7, 9)
    ActiveDocument.Range(0, 0).Text = strID
End Sub

Open in new window

0
 
MariaJoyalAuthor Commented:
This returns the ID exactly as I need it!  The only adjustment would be that I would like the ID wherever my cursor is.  This places the ID at the beginnng of the document.  

The only variables going forward would be when we reach document numbers over 999999 and, more immediate, versions over 9.

This is soooo cool!  Thank you.
0
 
MariaJoyalAuthor Commented:
Beautiful.  One last question...  Is it possible that this could be a field name that would automatically update as the file is resaved and thus has a new name?
0
 
GrahamSkanRetiredCommented:
Unfortunately not. There is a filename field, but there are no field functions for that can manipulate the text. You could use a bookmark and run this modified code.

Sub InsertID()
    Dim strFileName As String
    Dim strID As String
    Dim strBookmark As String
    Dim rng As Range
    
    strBookmark = "FileID"
    strFileName = ActiveDocument.Name 'e.g. "DOCS-#585185-v1-GENERAL_FORMS___Audit_Letter.docx."
    strID = Mid(strFileName, 7, 9)
    Set rng = ActiveDocument.Bookmarks(strBookmark).Range
    rng.Text = strID
    ActiveDocument.Bookmarks.Add strBookmark, rng 're-add bookmark to ensure that it contains the text
End Sub

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.