Microsoft Word 2013 macro save file name from form content

我只是一个虾纸丫 提交于 2020-01-03 06:01:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!