卡饭网 > 其他 > 正文

如何存储并检索Word文档中的变量

来源:本站整理 作者:梦在深巷 时间:2017-05-22 10:16:38

Microsoft 提供的编程示例仅用于说明,对其不做任何明示或暗示的保证。这包括但不限于对适销性或特定用途适用性的暗示保证。本文假定您熟悉所演示的编程语言及用于创建和调试过程的工具。Microsoft 支持工程师可以帮助解释某个特定过程的功能,但他们不会修改这些示例以使其具有可以满足特定需要的额外功能或构建过程。

您可以使用 Microsoft Visual Basic for Applications Variables 集合在 Word 文档或模板中设置和检索字符串变量的内容。

同时,您也可以将文档变量的值设置为在 Word 文档中显示之后,使用 DocVariable 域对其进行检索。

如何设置和检索文档变量的值

下面的示例宏使用 Variables 属性通过当前文档来存储并检索名为“FullName”的字符串变量的值。

Sub GetSetDocVars()

   Dim fName As String   fName = "Jeff Smith"   ' Set contents of variable "fName" in a document using a document   ' variable called "FullName".   ActiveDocument.Variables.Add Name:="FullName", Value:=fName   ' Retrieve the contents of the document variable.   MsgBox ActiveDocument.Variables("FullName").Value

End Sub

注意:如果在文档中已经设置了变量名称,则将出现下面的错误消息:

Run-Time Error "5903": The Variable name already exists.

您必须删除该名称,或者重置值参数即可。

如何删除文档变量

下面的示例宏使用 Variables 属性首先设置并检索文档变量的值,然后再从活动文档中删除该变量。

Sub GetSetDeleteDocVars()

   Dim fName As String   fName = "Jeff Smith"   ' Set contents of variable "fName" in a document using a document   ' variable called "FullName."   ActiveDocument.Variables.Add Name:="FullName", Value:=fName   ' Retrieve the contents of the document variable.   MsgBox ActiveDocument.Variables("FullName").Value   ' Delete the variable.   ActiveDocument.Variables("FullName").Delete

End Sub

如何使用 DocVariable 域检索文档变量的值

下面的示例宏使用 Variables 属性来设置文档变量。按照示例宏的步骤进行操作,以使用 DocVariable 域将值检索到同一文档的内容中。

Sub GetSetDocVars()

   Dim fName As String   fName = "Jeff Smith"   ' Set contents of variable "fName" in a document using a document   ' variable called "FullName."   ActiveDocument.Variables.Add Name:="FullName", Value:=fName

End Sub

要使用 DocVariable 域,请按照下列步骤进行操作:

  1. 在“插入”菜单上,单击“域”。

    注意:在 Microsoft Office Word 2007 中,单击“插入”选项卡上“文本”组中的“文档部件”,然后单击“域”。

  2. 在“类别”框中,选择“文档自动化”。

  3. 在“域名”列表中,选择“DocVariable”。

  4. 在“域属性”下的“新名称”框中,键入文档变量的名称。

    注意:如果您看到的是“高级域属性”而不是“域属性”,请单击“隐藏代码”。

  5. 单击“确定”。

如果您需要保留宏会话之间的值,则可以使用下列任一方法存储该值:

  • 使用 PrivateProfileString 属性将这些值存储到一个专用设置文件中。

    有关 PrivateProfileString 属性的更多信息,请在 Visual Basic 编辑器中,单击“帮助”菜单上的“Microsoft Visual Basic 帮助”,在 Office 助手或应答向导中键入“PrivateProfileString 属性”,然后单击“搜索”以查看主题。

  • 使用 Variables 属性存储文档中的值。

    有关 Variables 属性的更多信息,请在 Visual Basic 编辑器中,单击“帮助”菜单上的“Microsoft Visual Basic 帮助”,在 Office 助手或应答向导中键入“Variables 属性”,然后单击“搜索”以查看主题。

  • 使用 Visual Basic for Applications Input/Output 语句写入到文本文件(例如,Write 语句或 Print 语句)。

    有关将数据写入文件的更多信息,请在 Visual Basic 编辑器中,单击“帮助”菜单上的“Microsoft Visual Basic 帮助”,在 Office 助手或应答向导中键入“将数据写到文件中”,然后单击“搜索”以查看主题。

  • 使用 AutoTextEntry 对象存储“自动图文集”词条中的值。
    有关 AutoTextEntry 对象的更多信息,请在 Visual Basic 编辑器中,单击“帮助”菜单上的“Microsoft Visual Basic 帮助”,在 Office 助手或应答向导中键入“AutoTextEntry 对象”,然后单击“搜索”以查看主题。

相关推荐