问题
I'm trying to write a macro that will save a Microsoft Word 2013 document with a specific filename. I have created a word form that a client fills out. I would like to create a macro that automatically saves the document with the name of one of the fields that the client fills out 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
I'm fairly new to programming however, I do have some experience. I would greatly appreciate all the help that I can get here.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/32047917/microsoft-word-2013-macro-save-file-name-from-form-content