WORD文档在打印时会出现“第一节的页边距设于可打印区域之外”的对话框,所以,我在代码中,没有隐藏WORD APPLICATION窗口,我只是模拟打印,请楼主再实测一下。
关于WORD宏替换空格的事宜,我稍后再作回复。
以下代码分别在SHEET1的CHANGE事件中和该工作薄的模块1中。
其中的模块1,需要确认引用了microsoft word 10.0(版本而异)object library
以下代码供参考:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$D$4" Then
If MsgBox("您确信在" & [D3] & ".Doc文档中," & vbCrLf & "搜索此账号:[" & [D4] & "]并打印之?", vbYesNo + vbExclamation) = vbYes Then
Call PrintInWordPages
End If
End If
End Sub
'----------------------
Sub PrintInWordPages()
Dim WdApp As Word.Application, WdDoc As Word.Document
Dim DocFullName As String, FindString As String, PageItem As String
Dim Fcount As Integer
On Error Resume Next '忽略错误
'获得文档路径
DocFullName = ThisWorkbook.Path & "\" & ActiveSheet.[D3] & ".Doc"
FindString = ActiveSheet.[D4] '获得搜索字符
'如果找不到该文档,则友情提示并退出程序
If Dir(DocFullName) = "" Then MsgBox "Excel没有找到" & DocFullName & " ,请确认WORD文档名是否正确!", vbExclamation, "Warnning": Exit Sub
Set WdApp = New Word.Application '定义一个新的WORD Application
WdApp.Visible = True '显示程序窗口
'定义一个WdDoc文档,为指定打开的文档
Set WdDoc = WdApp.Documents.Open(FileName:=DocFullName)
With WdDoc.ActiveWindow.Selection
.HomeKey wdStory '移到文档首位置
.Find.ClearFormatting '清除查找格式
Do While .Find.Execute(findtext:=FindString) '搜索指定字符
'页数为字符型文本累加
PageItem = PageItem & "," & .Information(wdActiveEndPageNumber)
Fcount = Fcount + 1 '计数
Loop
'如果没有找到,则友情提示
If Fcount = 0 Then MsgBox "Word没有搜索到您要查找的账号[" & FindString & "],请核对!", vbExclamation, "Warnning"
'去掉第一个","号
PageItem = VBA.Mid(PageItem, 2, Len(PageItem) - 1)
' MsgBox PageItem
'WdDoc打印指定页数
WdDoc.PrintOut Range:=wdPrintRangeOfPages, Copies:=1, Pages:=PageItem
WdDoc.Close False
End With
WdApp.Quit '退出WORD
Set WdApp = Nothing '释放对象变量
End Sub
'----------------------
j0V7G1jy.rar
(11.24 KB, 下载次数: 34)
[此贴子已经被作者于2005-4-24 6:26:01编辑过] |