如何利用VBA編寫控制Word域的功能
Word 域在軟件開發(fā)中的應(yīng)用liyu摘要 域是Word 最具有實(shí)用價(jià)值的功能之一, 它表示文檔中可能發(fā)生變化的數(shù)據(jù)或郵件合并文檔中套用信函、標(biāo)簽中的占位符。Microsoft Word 可以在您使用
Word 域在軟件開發(fā)中的應(yīng)用
liyu
摘要 域是Word 最具有實(shí)用價(jià)值的功能之一, 它表示文檔中可能發(fā)生變化的數(shù)據(jù)或郵件合并文檔中套用信函、標(biāo)簽中的占位符。Microsoft Word 可以在您使用一些特定命令時(shí)插入域,如“插入”菜單上的“日期和時(shí)間”命令。您也可使用“插入”菜單上的“域”命令手動(dòng)插入域。
1. 引言
事實(shí)上,我們?cè)谌粘9ぷ髦谐?huì)脫離Microsoft Word 的操作環(huán)境。一般,用戶是先建立好一些Word 文件模板,然后利用所提供的應(yīng)用程序功能向Word 文件模板中插入域,然后用該域?qū)?yīng)的值取代域值,這樣就達(dá)到了向Microsoft Word 文件中插入數(shù)據(jù)的作用。我們常把數(shù)據(jù)放入數(shù)據(jù)庫中,數(shù)據(jù)庫的內(nèi)容不斷地變化,我們的域值也跟著不斷地變化,取到靈活自動(dòng)更新的作用,要達(dá)到這方面的功能,就應(yīng)該把數(shù)據(jù)庫與Word 域結(jié)合起來。
首先要解決這一問題,我們必須先了解Word 域有關(guān)的知識(shí):Word 域代碼位于花括號(hào)或大括號(hào) ( { } ) 中,域類似于 Microsoft Excel 中的公式:域代碼類似于公式,域結(jié)果(域結(jié)果:當(dāng) Microsoft Word 執(zhí)行域指令時(shí),在文檔中插入的文字或圖形。在打印文檔或隱藏域代碼時(shí),將以域結(jié)果替換域代碼。)類似于公式產(chǎn)生的值。可在文檔中切換顯示域代碼及其結(jié)果。正好,數(shù)據(jù)庫的字段名對(duì)應(yīng)域代碼,字段值對(duì)應(yīng)域結(jié)果。
,2. 實(shí)現(xiàn)功能
下面是本人利用VBA 編寫的一通用的處理Word 域的程序:
主要功能:通用VB6編寫通用的類,給用戶提供可視化的編輯界面,用于用戶在Word 文件中插入域標(biāo)志。針對(duì)Word 文件或Excel 表格文件,掃描整個(gè)文件,將其中的域標(biāo)志(如Set “aaa ”)取出來,然后通過從數(shù)據(jù)庫中取出”aaa ”字段所對(duì)應(yīng)的值,將值填寫到文件中域?qū)?yīng)的位置。若對(duì)應(yīng)位置已有值,則判斷該值與要填寫的值是否相同,若不同則替換。插入值分為:
A. 單純的值,直接使用一個(gè)值替換域。
B. 表格中的單元格。若該表格填寫不下,是否增加表格單元?以及與該單元關(guān)聯(lián)的域等。
3. 操作步驟
3.1建立項(xiàng)目
開發(fā)方法:?jiǎn)?dòng)VB6,新建一ActiveX Dll 工程,把工程名更改為VbaWord ,把類名Class1更改為CSetDocField ,向工程中增加一窗體Form1, 窗體標(biāo)題為處理Word 文檔,在Form1上加入2個(gè)CommandButton ,用于打開文件和保存文件用的命令按鈕;2個(gè)ComboBox ,用于所插入的字段名;2個(gè) Label;2個(gè)CommonDialog ,用于執(zhí)行打開文件和保存文件。界面如下:
3.2在項(xiàng)目中加入引用
按工程--引用--Microsoft Word 10.0 Object Library引用Word(OFFICE 2000為Microsoft Word 9.0 Object Library)。
3.3增加操作窗體
在Form1的代碼窗中定義以下變量:
Option Base 0
' 申請(qǐng)Word 應(yīng)該對(duì)象及文檔對(duì)象
Private wdApp As New Word.Application()
Private wdDoc As New Word.Document()
' 所處理的Word 模板
Private FileName As String
' 申請(qǐng)CSetDocField 對(duì)象
,Private mDocFld As New CSetDocField()
'Word 工具欄對(duì)象及菜單欄對(duì)象
Dim CommandBarIndex() As Integer
Dim SaveCommandBarMenuIndex() As Integer
' 在Form 的Load 的事件中定義的打開和保存文件的格式,并填充ComboBox 數(shù)據(jù)。ComboBox 數(shù)據(jù)對(duì)應(yīng)數(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 應(yīng)該對(duì)象及文檔對(duì)象, 并打開文件。
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:域的關(guān)鍵字.
這里我們利用Word 文檔對(duì)象的域?qū)ο蟮腁dd 方法向Word 文件中插入域。域的Data 屬性代表該域的名稱。插入域時(shí)應(yīng)該選取得插入點(diǎn)(Selection),既用戶光標(biāo)處位置。如果該位置是單
,元格且已插入域應(yīng)該提示是否覆蓋
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 '插入點(diǎn)
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
' 選擇點(diǎn)(光標(biāo)) 是否是單元格.
我們可以通過選擇點(diǎn)的表格數(shù)判斷插入點(diǎn)的性質(zhì)。表格數(shù)為0,則選擇點(diǎn)不位于單元格中,反則不位于單元格中。
Private Function IsCell(ByVal mySelection As Selection) As Boolean
If mySelection.Tables.Count > 0 Then
IsCell = True
Else
IsCell = False
End If
End Function
' 取得選擇點(diǎn)(光標(biāo)) 的單元格的域數(shù)
Private Function CellFieldCount(ByVal mySelection As Selection) As Integer CellFieldCount = mySelection.Cells(1).Range.Fields.Count
End Function
' 打開Word 文件. 并使處理界面位于Word 最頂端,適當(dāng)調(diào)整Word 位置,關(guān)閉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
' 用戶選擇所插入域的域名,并在光標(biāo)處插入域。 Private Sub Combo1_Click()
Dim KeyWord As String
KeyWord = Combo1.Text
InsertField(KeyWord)
End Sub
,' 用戶選擇所插入域的域名,并在光標(biāo)處插入域。
域所對(duì)應(yīng)多值時(shí),域只能插入表格中。且要與單值域區(qū)分,標(biāo)記為多值插入。
Private Sub Combo2_Click()
Dim KeyWord As String
mySelection = wdApp.Selection '插入點(diǎn)
If IsCell(mySelection) <> True Then
MsgBox("該位置不是單元格, 請(qǐng)選擇單元格", vbOKOnly vbExclamation) Exit Sub
End If
KeyWord = Combo2.Text "F" '標(biāo)記是多值
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
' 在關(guān)閉該界面時(shí)應(yīng)該恢復(fù)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
' 關(guān)閉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
' 恢復(fù)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 類的內(nèi)容。
CSetDocField 類應(yīng)該提供單值域和多值的域名,所以我們把它們定義為CSetDocField 類的屬性,并提供一運(yùn)行上面窗口的方法。這里我們要利用一些技巧,在定義類并向類屬性賦性值后,事實(shí)賦性值是保存在所定義的實(shí)類中,該實(shí)類一旦消失,值也隨著消失。如何不通過該實(shí)類取得類的屬性?這是困擾許多開發(fā)人員的問題。我的解決方法是申請(qǐng)與類屬性對(duì)應(yīng)的全局變量。向類屬性的同時(shí),把值保存在對(duì)應(yīng)的全局變量中,取值時(shí)取出對(duì)應(yīng)的全局變量的值就可。
這里我們選增加一Module, 其Code 如下:
Public gSavePath As String
Public gFieldColl As Collection
Public gTableColl As Collection
Sub Main()
Form1.Show(1)
End Sub
下面我利用全局變量當(dāng)作類屬性使用的技巧:
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 文件。
下面編寫將值填寫到文件中域?qū)?yīng)的位置的類。
在VbaWord 工程中增加新類CWriteDataToDocument 。
類CWriteDataToDocument 由調(diào)用者提供所處理的文件模板,所以它應(yīng)該有一文檔屬性
DocumentName ,打開DocumentName 文件,向DocumentName 文件中插入單值和多值。插入多值時(shí)要判斷是否增加單元格。如果對(duì)應(yīng)的值多于所提供的表格行數(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