word构建基块、自动图文集可以将常用的文本、段落、表格、图表、图片等储存起来。
如下图所示:

通过构建基块、自动图文集,可以快速地添加常用的文本、段落、表格、图表、图片。
比如一个构建基块、自动图文集命名为”常用内容”,只要输入常用内容,然后按下F3就可以将这个名称对应的内容自动插入到word文档中。
word中自动图文集属于构建基块的一部分。
构建基块都是存储在模板中的,如下图所示:

在word vba中 AutoTextEntries 对象表示自动图文集对象集合,除了可以通过AutoTextEntries 对象访问自动图文集对象,还可以通过BuildingBlockEntries 构建基块项目集合对象或BuildingBlocks构建基块项目集合对象访问自动图文集。
其中构建基块的库名组成了BuildingBlockTypes集合对象,构建基块的类别组成了Categories集合对象。
接下来介绍用word vba实现构建基块的添加、删除、读取、修改等操作。
一、用VBA遍历某个模板内的所有构建基块
以下代码是用VBA遍历某个模板内的所有构建基块:
Sub QQ1722187970()
Dim oBB As BuildingBlock
Dim oBBT As BuildingBlockType
Dim oBBC As Category
Dim oTP As Template
Dim oDoc As Document
Dim oRng As Range
Set oDoc = Word.ActiveDocument
With oDoc
Set oTP = .AttachedTemplate
Debug.Print oTP.Name
With oTP
For i = 1 To .BuildingBlockEntries.Count
Set oBB = .BuildingBlockEntries(i)
With oBB
'构建基块的名称
sName = .Name
'构建基块的值
sValue = .Value
'构建基块的说明
sDescription = .Description
Set oBBT = .Type
'构建基块的库名
sTypeName = oBBT.Name
Set oBBC = .Category
'构建基块的类别名称
sCName = oBBC.Name
Debug.Print sName, sTypeName, sCName, sDescription, sValue
End With
Next
End With
End With
End Sub
二、用vba新增、修改构建基块
以下代码举例演示了如何用BuildingBlockEntries对象的Add方法新增构建基块、如何修改原来的构建基块:
Sub QQ1722187970()
Dim oBB As BuildingBlock
Dim oBBT As BuildingBlockType
Dim oBBC As Category
Dim oTP As Template
Dim oDoc As Document
Dim oRng As Range
Set oDoc = Word.ActiveDocument
With oDoc
Set oRng = Word.Selection.Range
Set oTP = .AttachedTemplate
Debug.Print oTP.Name
With oTP
'添加库名为文档部件,类别为No2的构建基块
Set oBB = .BuildingBlockEntries.Add("test", wdTypeQuickParts, "No2", oRng)
'库名、类别、名称都不变的话相当于直接修改原来的构建基块
Set oBB = .BuildingBlockEntries.Add("test", wdTypeQuickParts, "No2", oRng)
'库名、类别任意一个改变的话相当于新增一个同名称的不同库名或不同类别的构建基块
Set oBB = .BuildingBlockEntries.Add("test", wdTypeAutoText, "No2", oRng)
End With
End With
End Sub
三、用VBA插入、删除构建基块的内容
如果要插入构建基块的内容,可以使用BuildingBlock对象的Insert方法。
如果要删除构建基块的内容,可以用BuildingBlock对象Delete方法。
Sub QQ1722187970()
Dim oBB As BuildingBlock
Dim oBBT As BuildingBlockType
Dim oBBC As Category
Dim oTP As Template
Dim oDoc As Document
Dim oRng As Range
Set oDoc = Word.ActiveDocument
With oDoc
Set oRng = Word.Selection.Range
oRng.Collapse wdCollapseEnd
Set oTP = .AttachedTemplate
Debug.Print oTP.Name
With oTP
For i = 1 To .BuildingBlockEntries.Count
Set oBB = .BuildingBlockEntries(i)
With oBB
'构建基块的名称
sName = .Name
'构建基块的值
sValue = .Value
'构建基块的说明
sDescription = .Description
Set oBBT = .Type
'构建基块的库名
sTypeName = oBBT.Name
Set oBBC = .Category
'构建基块的类别名称
sCName = oBBC.Name
Debug.Print sName, sTypeName, sCName, sDescription, sValue
If sName = "test" Then
' oBB.Delete
' '插入一个构建基块,同时返回构建基块所在的range区域
Set oRng = oBB.Insert(oRng, True)
'oRng区域对象折叠为oRng对象的结尾
oRng.Collapse wdCollapseEnd
End If
End With
Next
End With
End With
End Sub


设置那么多变量有必要吗?
不好!变量设置太多