|
1、在你的WORD文档中选择“工具”——”宏“——”Visual Basic 编辑器“
2、弹出Visual Basic 编辑器后选择“Project(你的文档名)——”Microsoft Word 对象“——“ThisDocument”
3、将下列代码拷贝到代码窗口
4、修改“strExcel”、“strSheet”两个参数的值
5、保存。OK
'以下是代码
'code read environment variable with API
Private Declare Function GetEnvironmentVariable Lib "kernel32.dll" Alias "GetEnvironmentVariableA" (ByVal lpName As String, ByVal lpBuffer As String) As Long
Public Function GetVar(strName As String)
Dim strBuffer As String
Dim lngLen As Long
lngLen = 256
strBuffer = String$(lngLen, Chr$(0))
lngLen = GetEnvironmentVariable(strName, strBuffer, lngLen)
If lngLen <> 0 Then
strBuffer = Left(strBuffer, lngLen)
GetVar = strBuffer
End If
End Function
Private Sub Document_Close()
'this necessary if you don't want it ask you to open datasource every time doc is opened
Me.MailMerge.MainDocumentType = wdNotAMergeDocument
Me.Save
End Sub
Private Sub Document_Open()
Dim strExcel As String
Dim strSheet As String
Dim strDataSource As String
Dim strConnection As String
Dim strQuery As String
Dim tempPath As String
tempPath = Me.Path
strExcel = "三非案件资料"
strSheet = "讨论1"
' set this to be the file name of your data source
strDataSource = tempPath & "\" & strExcel & ".xls"
' set this to be the connection string for your data source
strConnection = ""
strQuery = "select * from " & strDataSource 'MMerge.TXT"
With ActiveDocument
With MailMerge
.OpenDataSource Name:= _
strDataSource, _
ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
Format:=wdOpenFormatAuto, Connection:= _
"Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=" & strDataSource & ";Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:RegistryPath="""";Jet OLEDB:Database Password", SQLStatement:="SELECT * FROM `" & strSheet & "$`", SQLStatement1:="", SubType:= _
wdMergeSubTypeAccess
End With
End With
End Sub
|
|