Extract section of text from a form field

J

johnnykunst

I am creating a filename from form fields using:
Private Sub CommandButton1_Click()
Dim pStr As String
pStr = "C:\Users\John\Desktop\" 'Your directory
pStr = pStr + ActiveDocument.FormFields("nameDD").Result
pStr = pStr + " "
pStr = pStr + ActiveDocument.FormFields("classificationDD").Result
pStr = pStr + " "
pStr = pStr + ActiveDocument.FormFields("wardDD").Result
pStr = pStr + " .docx"
ActiveDocument.SaveAs FileName:=pStr
Dim sCode As String
MsgBox "Your Intelligence report was saved to the central WINTEL inbox for processing & emailing. No further action is required; it is now safe to close the document"
End Sub

However, what i would like to do is for the "nameDD" only use part of the text- we use identification codes for each memeber of staff such as C832, E840, KA345, M65. As you can see, these codes vary in the number of characters. The codes are used to prefix names in the drop down- what I want to do is to extract just the characters from before a "-" (or other mark) so that from "C832- J Wirth" only the "C832" would be extracted, for "M64- S Hunter" only the M64 would be extracted, despite the first example being 4 characters, and the second example being 3 characters.
Help is very much appreciated.
 
J

Jay Freedman

Replace your line that mentions "nameDD" with this:

pStr = pStr + Split( _
ActiveDocument.FormFields("nameDD").Result, "-")(0)

The Split function with "-" as the second parameter creates an array
containing two strings: the text before the hyphen as element 0 and
the text after the hyphen as element 1. (I assume that formfield
nameDD is a dropdown, so you can guarantee that each entry has a
hyphen after the identification code.) Then the (0) at the end selects
the first string and attaches it to pStr.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top