如何利用VBA編寫控制Word域的功能
Word 域在軟件開發(fā)中的應用liyu摘要 域是Word 最具有實用價值的功能之一, 它表示文檔中可能發(fā)生變化的數(shù)據(jù)或郵件合并文檔中套用信函、標簽中的占位符。Microsoft Word 可以在您使用


Word 域在軟件開發(fā)中的應用
liyu
摘要 域是Word 最具有實用價值的功能之一, 它表示文檔中可能發(fā)生變化的數(shù)據(jù)或郵件合并文檔中套用信函、標簽中的占位符。Microsoft Word 可以在您使用一些特定命令時插入域,如“插入”菜單上的“日期和時間”命令。您也可使用“插入”菜單上的“域”命令手動插入域。
1. 引言
事實上,我們在日常工作中常會脫離Microsoft Word 的操作環(huán)境。一般,用戶是先建立好一些Word 文件模板,然后利用所提供的應用程序功能向Word 文件模板中插入域,然后用該域對應的值取代域值,這樣就達到了向Microsoft Word 文件中插入數(shù)據(jù)的作用。我們常把數(shù)據(jù)放入數(shù)據(jù)庫中,數(shù)據(jù)庫的內容不斷地變化,我們的域值也跟著不斷地變化,取到靈活自動更新的作用,要達到這方面的功能,就應該把數(shù)據(jù)庫與Word 域結合起來。
首先要解決這一問題,我們必須先了解Word 域有關的知識:Word 域代碼位于花括號或大括號 ( { } ) 中,域類似于 Microsoft Excel 中的公式:域代碼類似于公式,域結果(域結果:當 Microsoft Word 執(zhí)行域指令時,在文檔中插入的文字或圖形。在打印文檔或隱藏域代碼時,將以域結果替換域代碼。)類似于公式產(chǎn)生的值??稍谖臋n中切換顯示域代碼及其結果。正好,數(shù)據(jù)庫的字段名對應域代碼,字段值對應域結果。
,2. 實現(xiàn)功能
下面是本人利用VBA 編寫的一通用的處理Word 域的程序:
主要功能:通用VB6編寫通用的類,給用戶提供可視化的編輯界面,用于用戶在Word 文件中插入域標志。針對Word 文件或Excel 表格文件,掃描整個文件,將其中的域標志(如Set “aaa ”)取出來,然后通過從數(shù)據(jù)庫中取出”aaa ”字段所對應的值,將值填寫到文件中域對應的位置。若對應位置已有值,則判斷該值與要填寫的值是否相同,若不同則替換。插入值分為:
A. 單純的值,直接使用一個值替換域。
B. 表格中的單元格。若該表格填寫不下,是否增加表格單元?以及與該單元關聯(lián)的域等。
3. 操作步驟
3.1建立項目
開發(fā)方法:啟動VB6,新建一ActiveX Dll 工程,把工程名更改為VbaWord ,把類名Class1更改為CSetDocField ,向工程中增加一窗體Form1, 窗體標題為處理Word 文檔,在Form1上加入2個CommandButton ,用于打開文件和保存文件用的命令按鈕;2個ComboBox ,用于所插入的字段名;2個 Label;2個CommonDialog ,用于執(zhí)行打開文件和保存文件。界面如下:

3.2在項目中加入引用
按工程--引用--Microsoft Word 10.0 Object Library引用Word(OFFICE 2000為Microsoft Word 9.0 Object Library)。
3.3增加操作窗體
在Form1的代碼窗中定義以下變量:
Option Base 0
' 申請Word 應該對象及文檔對象
Private wdApp As New Word.Application()
Private wdDoc As New Word.Document()
' 所處理的Word 模板
Private FileName As String
' 申請CSetDocField 對象
,Private mDocFld As New CSetDocField()
'Word 工具欄對象及菜單欄對象
Dim CommandBarIndex() As Integer
Dim SaveCommandBarMenuIndex() As Integer
' 在Form 的Load 的事件中定義的打開和保存文件的格式,并填充ComboBox 數(shù)據(jù)。ComboBox 數(shù)據(jù)對應數(shù)據(jù)庫表的字段名,這里由CSetDocField 的屬性提供。
Private Sub Form_Load()
Dim i As Integer
CommonDialog1.DialogTitle = "打開"
CommonDialog1.Filter = "Word文檔(*.doc)|*.doc|Word文檔模板(*.dot)|*.dot"
CommonDialog2.DialogTitle = "保存文件"
CommonDialog2.Filter = Word文檔(*.doc)|*.doc|Word文檔模板(*.dot)|*.dot" FieldCount = 0
Me.ScaleY(Me.height, fromscale:=vbTwips, toscale:=vbPoints)
For i = 1 To gFieldColl.Count
Combo1.AddItem(gFieldColl.Item(i))
Next
For i = 1 To gTableColl.Count
Combo2.AddItem(gTableColl.Item(i))
Next
End Sub
在Form1的代碼窗中定義以下過程和函數(shù):
' 定義打開Word 文件的過程。建立Word 應該對象及文檔對象, 并打開文件。
Private Sub OpenWordDocument(ByVal FileName As String)
wdApp = CreateObject("Word.Application")
wdApp.Documents.Open(FileName)
wdDoc = wdApp.ActiveDocument
wdDoc.ActiveWindow.DocumentMap = False
wdApp.Visible = True
IsWordRunning = True
End Sub
' 在文檔中插入域.KeyWord:域的關鍵字.
這里我們利用Word 文檔對象的域對象的Add 方法向Word 文件中插入域。域的Data 屬性代表該域的名稱。插入域時應該選取得插入點(Selection),既用戶光標處位置。如果該位置是單
,元格且已插入域應該提示是否覆蓋
Private Function InsertField(ByVal KeyWord As String) As Integer
Dim mySelection As Selection
Dim Code As String
Dim MyField As Field
Dim myRange As Range
wdApp.Selection.Collapse(Direction:=wdCollapseEnd)
mySelection = wdApp.Selection '插入點
If IsCell(mySelection) = True Then
If CellFieldCount(mySelection) > 0 Then
If MsgBox("該單元格已有域, 是否覆蓋?", vbYesNo) = 6 Then
mySelection.Cells(1).Select()
mySelection.Delete() ' .Text = Value
' mySelection.Delete Unit:=wdCharacter, Count:=1
'mySelection.Cells(1).Range.Fields(1).Delete
Else
Exit Function
End If
End If
End If
MyField = wdDoc.Fields.Add(Range:=mySelection.Range, Type:=wdFieldAddin) MyField.Data = KeyWord
End Function
' 選擇點(光標) 是否是單元格.
我們可以通過選擇點的表格數(shù)判斷插入點的性質。表格數(shù)為0,則選擇點不位于單元格中,反則不位于單元格中。
Private Function IsCell(ByVal mySelection As Selection) As Boolean
If mySelection.Tables.Count > 0 Then
IsCell = True
Else
IsCell = False
End If
End Function
' 取得選擇點(光標) 的單元格的域數(shù)
Private Function CellFieldCount(ByVal mySelection As Selection) As Integer CellFieldCount = mySelection.Cells(1).Range.Fields.Count
End Function
' 打開Word 文件. 并使處理界面位于Word 最頂端,適當調整Word 位置,關閉Word 其它功能。 Private Sub cmdOpenFile_Click()
,CommonDialog1.ShowOpen()
FileName = CommonDialog1.FileName
If FileName = "" Then
Exit Sub
End If
OpenWordDocument(FileName)
IsShowField(True)
SetWordSize(0, 42, 2000, 2000)
CloseCommandBar()
Me.top = 0
Me.Left = 0
Me.width = 100000
Me.height = 850
Picture1.top = Me.top
Picture1.Left = Me.Left 2000
cmdSave.Left = 2000
cmdSave.top = cmdOpenFile.top
Combo1.Enabled = True
Combo2.Enabled = True
cmdSave.Visible = True
cmdOpenFile.Visible = False
End Sub
' 保存Word 文件.
Private Sub cmdSave_Click()
IsShowField(False)
CommonDialog2.FileName = gSavePath FileName CommonDialog2.FileName = gSavePath FileName CommonDialog2.ShowSave()
wdDoc.SaveAs(CommonDialog2.FileName) End Sub
' 用戶選擇所插入域的域名,并在光標處插入域。 Private Sub Combo1_Click()
Dim KeyWord As String
KeyWord = Combo1.Text
InsertField(KeyWord)
End Sub
,' 用戶選擇所插入域的域名,并在光標處插入域。
域所對應多值時,域只能插入表格中。且要與單值域區(qū)分,標記為多值插入。
Private Sub Combo2_Click()
Dim KeyWord As String
mySelection = wdApp.Selection '插入點
If IsCell(mySelection) <> True Then
MsgBox("該位置不是單元格, 請選擇單元格", vbOKOnly vbExclamation) Exit Sub
End If
KeyWord = Combo2.Text "F" '標記是多值
InsertField(KeyWord)
End Sub
Private Sub Form_Load()
Dim i As Integer
CommonDialog1.DialogTitle = "打開"
CommonDialog1.Filter = "Word文檔(*.doc)|*.doc|Word文檔模板(*.dot)|*.dot"
CommonDialog2.DialogTitle = "保存文件"
CommonDialog2.Filter = "Word文檔(*.doc)|*.doc|Word文檔模板(*.dot)|*.dot" FieldCount = 0
Me.ScaleY(Me.height, fromscale:=vbTwips, toscale:=vbPoints)
For i = 1 To gFieldColl.Count
Combo1.AddItem(gFieldColl.Item(i))
Next
For i = 1 To gTableColl.Count
Combo2.AddItem(gTableColl.Item(i))
Next
End Sub
'**********************************************************
Private Function InsertFieldByKeyWord(ByVal KeyWord As String) As Integer Dim ID As Integer
FieldCount = FieldCount 1
ReDim MyField(FieldCount)
ID = InsertField(KeyWord)
,MyField(FieldCount).ID = ID
MyField(FieldCount).KeyWord = KeyWord
End Function
Private Sub SetEnabled(ByVal isEnabled As Boolean)
Dim obj As Control
For Each obj In Me.Controls
If TypeName(obj) = "TextBox" Then
obj.Enabled = isEnabled
End If
If TypeName(obj) = "ComboBox" Then
obj.Enabled = isEnabled
End If
If TypeName(obj) = "CheckBox" Then
obj.Enabled = isEnabled
End If
If TypeName(obj) = "CommandButton" Then
obj.Enabled = isEnabled
End If
Next
End Sub
' 在關閉該界面時應該恢復Word 環(huán)境。
Private Sub Form_Unload(ByVal Cancel As Integer)
If FileName <> "" Then
OpenCommandBar()
wdApp.ActiveWindow.Close()
wdApp.Quit()
End If
End Sub
' 定義Word 環(huán)境的大小。
Private Sub SetWordSize(ByVal Left As Integer, ByVal top As Integer, ByVal width As Integer, ByVal height As Integer)
wdApp.WindowState = wdWindowStateNormal
wdApp.Left = Left
wdApp.top = top
wdApp.width = width
wdApp.height = height
End Sub
' 定義Word 域代碼是否可顯示。
,Private Sub IsShowField(ByVal IsShow As Boolean)
wdApp.ActiveWindow.View.ShowFieldCodes = IsShow
End Sub
' 關閉Word 環(huán)境的所有命令及菜單。
Private Sub CloseCommandBar()
Dim i As Integer
Dim cBar
ReDim CommandBarIndex(1)
ReDim SaveCommandBarMenuIndex(1)
i = 0
For Each cBar In wdDoc.CommandBars
If cBar.Type = 0 And cBar.Enabled = True Then If cBar.Visible = True Then
ReDim CommandBarIndex(i 1)
CommandBarIndex(i) = cBar.Index
i = i 1
cBar.Visible = False
End If
End If
Next
i = 0
For Each cBar In wdDoc.CommandBars("Menu Bar").Controls If cBar.Visible = True Then
ReDim SaveCommandBarMenuIndex(i 1)
SaveCommandBarMenuIndex(i) = cBar.Index
i = i 1
cBar.Visible = False
End If
Next
End Sub
' 恢復Word 環(huán)境的所有命令及菜單。
Private Sub OpenCommandBar()
Dim i As Integer
For i = 0 To UBound(CommandBarIndex) - 1
wdDoc.CommandBars(i 1).Visible = True
Next
For i = 0 To UBound(SaveCommandBarMenuIndex) - 1
CommandBars("Menu Bar").Controls(i 1).Visible = True Next
End Sub
,3.2增加窗體
下面我們繼續(xù)編寫CSetDocField 類的內容。
CSetDocField 類應該提供單值域和多值的域名,所以我們把它們定義為CSetDocField 類的屬性,并提供一運行上面窗口的方法。這里我們要利用一些技巧,在定義類并向類屬性賦性值后,事實賦性值是保存在所定義的實類中,該實類一旦消失,值也隨著消失。如何不通過該實類取得類的屬性?這是困擾許多開發(fā)人員的問題。我的解決方法是申請與類屬性對應的全局變量。向類屬性的同時,把值保存在對應的全局變量中,取值時取出對應的全局變量的值就可。
這里我們選增加一Module, 其Code 如下:
Public gSavePath As String
Public gFieldColl As Collection
Public gTableColl As Collection
Sub Main()
Form1.Show(1)
End Sub
下面我利用全局變量當作類屬性使用的技巧:
CSetDocField 類的Code:
Public Sub Run()
Static FieldColl As Collection
Static TableColl As Collection
Main()
End Sub
Property Get FieldColl() As Collection
'Set FieldColl = mFieldColl
Set FieldColl = gFieldColl
End Property
Property Let FieldColl(Field As Collection)
Set gFieldColl = Field
End Property
Property Get TableColl() As Collection
Set TableColl = gTableColl
End Property
Property Let TableColl(Field As Collection)
Set gTableColl = Field
End Property
Property Let SavePath(str As String)
,gSavePath = str
End Property
這里,我們把插入域的類編寫好了,只要在VB6的文件菜單中執(zhí)行生成該類的文件就可生成DLL 文件。
下面編寫將值填寫到文件中域對應的位置的類。
在VbaWord 工程中增加新類CWriteDataToDocument 。
類CWriteDataToDocument 由調用者提供所處理的文件模板,所以它應該有一文檔屬性
DocumentName ,打開DocumentName 文件,向DocumentName 文件中插入單值和多值。插入多值時要判斷是否增加單元格。如果對應的值多于所提供的表格行數(shù),則要增加行。下面是它的完整Code:
Private wdApp As New Word.Application()
Private wdDoc As New Word.Document()
Private IsInsertRow As Boolean '是否已經(jīng)插入了行
Public DocumentName As String
Public Function FillData()
OpenWordDocument()
InsertValue()
InsertCollection()
wdDoc.SaveAs(DocumentName)
End Function
Public Function GetValueByField(ByVal FieldName As String) As String GetValueByField = "liyu"
End Function
Public Function GetRecordSetByField(ByVal FieldName As String) As Collection Dim coll As New Collection()
coll.Add("li")
coll.Add("yu")
GetRecordSetByField = coll
End Function
Private Sub OpenWordDocument()
wdApp = CreateObject("Word.Application")
wdApp.Documents.Open(DocumentName)
wdDoc = wdApp.ActiveDocument
wdApp.Visible = True
'wdDoc.ActiveWindow.DocumentMap = False
End Sub