---
title: "word 宏 更新域 VBA语法"
author: "e_e"
date: "2019-02-01T17:50:43Z"
tags: []
categories: ["开源软件"]
slug: "word-vba"
draft: false
lastmod: "2019-02-21T19:28:10Z"
id: 2437341
url: "https://e-e.iteye.com/blog/2437341"
---

打开一个word文档

 

第一步：定义宏

视图 中找到宏

输入宏名称setValue ，回车后编辑宏的内容如下

Sub setValue()

'

' setValue 宏

'

Dim doc\_var As Variable

    For Each doc\_var In ActiveDocument.Variables

        doc\_var.Delete

    Next

         ActiveDocument.Variables("name").value = "zhangyan"

         ActiveDocument.Variables("address").value = "shanghai"

         ActiveDocument.Variables("id\_card").value = "5223467899"

         ActiveDocument.Variables("school").value = "shlg"

End Sub

 

编辑完成后点击执行。

 

第二步：插入域

在word中插入域 =》文档自动化=》 DocVariabl

如果是mac 域名称前面有默认值DOCVARIABLE ，我们定义的域名要拼接在默认值后面

DOCVARIABLE  name

 

address id\_card school  同理

 

如果是修改操作，那么修改代码里的值，页面上选中所有的域-》更新域即可

 

 

==========================下面的宏是添加特殊字符，选择框==========================

Sub insert\_variable(key, value)

 

    On Error GoTo addValue

    ActiveDocument.Variables.Add Name:=key, value:=value

 

addValue:

    ActiveDocument.Fields.Add Selection.Range, wdFieldEmpty, "DOCVARIABLE " + key

 

End Sub

 

Sub insert\_special\_char(key)

    On Error GoTo addValue

    ActiveDocument.Variables.Add Name:=key, value:=ChrW("163")

addValue:

    preservedFont = Selection.Font.Name

    Selection.Font.Name = "Wingdings 2"

    ActiveDocument.Fields.Add Selection.Range, wdFieldEmpty, "DOCVARIABLE " + key

    Selection.Font.Name = preservedFont

    Selection.TypeText Text:=" "

End Sub

 

 

Sub add\_text()

    'insert\_variable "Serve\[2]", "{服务方\[1]}"

    insert\_special\_char "xxx\[c]"

End Sub