0
votes

I'm trying to save a Microsoft Word 2013 document with a specific filename.

I created a Word form that a client fills out.

I am using the following: DEVELOPER -> Controls -> Plain Text Content Control DEVELOPER -> Controls -> Date Picker Content Control DEVELOPER -> Controls -> Drop-Down List Content Control

I would like a macro to save the document with the name of one of the fields in the form.

Example:
below are fillable content fields.

client reference: A1B2-345
date: August 17, 2015
type: metadata

I would like to save the file as:

A1B2-345_17082015_metadata.DOCX
2
Automatically save it when? What triggers the save?Bond
Bond, actually, because of your comment I understand that I do not want to automatically save the document, rather save it upon running the macro.Eitan Waks
Are you using a Content Textbox, a legacy text form field, or an ActiveX text box?Bond
I'm not exactly sure. I am using the following: DEVELOPER -> Controls -> Plain Text Content Control DEVELOPER -> Controls -> Date Picker Content Control DEVELOPER -> Controls -> Drop-Down List Content ControlEitan Waks

2 Answers

0
votes

Start by giving each of your controls a Title. You can do this by clicking on your control in your document and then click Properties on the Developer ribbon. The first field on the Properties window is Title. Give each one of the controls you need to access a unique title. In the example below, I'm using MyText, MyDate, and MyDrop for the text, date, and drop-down controls, respectively.

Then you can access each control in VBA by using the SelectContentControlsByTitle() function. As long as you're using a unique title, this function will return a collection containing only a single control so we can just retrieve the first item from the collection (index (1)). Here's how this would look:

Dim strText As String, strDate As String, strDrop As String

strText = ThisDocument.SelectContentControlsByTitle("MyText")(1).Range.Text
strDate = ThisDocument.SelectContentControlsByTitle("MyDate")(1).Range.Text
strDrop = ThisDocument.SelectContentControlsByTitle("MyDrop")(1).Range.Text

The Range.Text ending is what grabs the current text/value from the control.

Now that you have your three pieces of information, you can concatenate them into one string using the concatenation operator (&):

Dim strFilename As String
strFilename = strText & "_" & Format(strDate, "ddmmyyyy") & "_" & strDrop & ".docx"

And, finally, save it:

ThisDocument.SaveAs strFilename
0
votes

It should be noted that the code provided above will not work properly if you are generating the form based off a template (.dotm). The following lines that include the ThisDocument.SelectContentControlsByTitle need to be changed to ActiveDocument.SelectContentControlsByTitle otherwise the code will pull the place holder text from the content control.