如何在VBA代码中按名称引用Word字段?
How to refer to Word Field by name in VBA Code?
我想使用 VBA 更新单词字段内容。我已经有一个有效的代码,但我必须引用字段的索引而不是字段的名称,这是我更喜欢的。
我的代码如下:
Sub UpdateField()
Dim myString As String
myString = "asdf"
ActiveDocument.Fields(1).Result.Text = myString
End Sub
假设字段名称是 MyField1。以下代码将不起作用(我收到 运行 时间错误“13”:类型不匹配。
Sub UpdateField()
Dim myString As String
myString = "asdf"
ActiveDocument.Fields("MyField1").Result.Text = myString
End Sub
我从文件菜单 > 信息 > 高级属性 > 自定义选项卡创建我的单词字段。
那么,当我们要更新字段的内容时,如何引用字段的名称呢?
在 VBE 中,对象浏览器 是了解可能性的好方法。当我找到 Word>Field 并单击它时,我会看到 Field 的成员列表。 姓名 不在该列表中。这意味着字段对象没有名称 属性。这就是您收到错误的原因。
您可以解决这个问题。一种方法是在相关字段周围创建书签。然后在代码中,通过名称找到书签,然后通过索引找到书签范围内的字段。
这些是 DocProperty
个字段。如果按 Alt+F9,您将看到字段 codes。
A DocProperty
字段引用(链接到)文档 属性。文档 属性 有名称,但这没有 "name" 字段。也不可能直接 更新 DocProperty
字段,因为它链接到文档 属性。可以让它暂时显示其他内容,但只要字段更新,这些内容就会丢失。
为了更新 DocProperty
字段,有必要更新基础文档 属性。例如
Sub EditDocPropUpdateDocPropertyField()
Dim doc As Word.Document
Dim prop As Office.DocumentProperty
Dim propName As String
Dim newPropValue As String
Set doc = ActiveDocument
propName = "MyField"
newPropValue = "new value"
Set prop = doc.CustomDocumentProperties(propName)
prop.value = newPropValue
doc.Fields.Update
End Sub
按字段名称将文本设置为字段的示例:
ThisDocument.FormFields.Item("MyField1").Result = "hello"
我想使用 VBA 更新单词字段内容。我已经有一个有效的代码,但我必须引用字段的索引而不是字段的名称,这是我更喜欢的。
我的代码如下:
Sub UpdateField()
Dim myString As String
myString = "asdf"
ActiveDocument.Fields(1).Result.Text = myString
End Sub
假设字段名称是 MyField1。以下代码将不起作用(我收到 运行 时间错误“13”:类型不匹配。
Sub UpdateField()
Dim myString As String
myString = "asdf"
ActiveDocument.Fields("MyField1").Result.Text = myString
End Sub
我从文件菜单 > 信息 > 高级属性 > 自定义选项卡创建我的单词字段。
那么,当我们要更新字段的内容时,如何引用字段的名称呢?
在 VBE 中,对象浏览器 是了解可能性的好方法。当我找到 Word>Field 并单击它时,我会看到 Field 的成员列表。 姓名 不在该列表中。这意味着字段对象没有名称 属性。这就是您收到错误的原因。
您可以解决这个问题。一种方法是在相关字段周围创建书签。然后在代码中,通过名称找到书签,然后通过索引找到书签范围内的字段。
这些是 DocProperty
个字段。如果按 Alt+F9,您将看到字段 codes。
A DocProperty
字段引用(链接到)文档 属性。文档 属性 有名称,但这没有 "name" 字段。也不可能直接 更新 DocProperty
字段,因为它链接到文档 属性。可以让它暂时显示其他内容,但只要字段更新,这些内容就会丢失。
为了更新 DocProperty
字段,有必要更新基础文档 属性。例如
Sub EditDocPropUpdateDocPropertyField()
Dim doc As Word.Document
Dim prop As Office.DocumentProperty
Dim propName As String
Dim newPropValue As String
Set doc = ActiveDocument
propName = "MyField"
newPropValue = "new value"
Set prop = doc.CustomDocumentProperties(propName)
prop.value = newPropValue
doc.Fields.Update
End Sub
按字段名称将文本设置为字段的示例:
ThisDocument.FormFields.Item("MyField1").Result = "hello"