vb控制word的类模块,查找、替换Word文档内容

  在VB6.0中,操作word,使用它强大的查找、替换、删除、复制、翦切功能。还可以把特定字符替换成图片。有了它你就可以使用数据库中的内容或图片文件替换word文件中的特定字符。

  只要把下列内容复制到写字板中,另存为SetWord.cls文件,然后在把它添加到工程中,就可以使用了。

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "SetWord"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Private mywdapp As Word.Application
Private mysel As Object

'属性值的模块变量
Private C_TemplateDoc As String
Private C_newDoc As String
Private C_PicFile As String
Private C_ErrMsg As Integer

Public Event HaveError()
Attribute HaveError.VB_Description = "出错时激发此事件.出错代码为ErrMsg属性"
'***************************************************************
'ErrMsg代码:1-word没有安装 2 - 缺少参数  3 - 没权限写文件
'           4 - 文件不存在
'
'***************************************************************

Public Function ReplacePic(FindStr As String, Optional Time As Integer = 0) As Integer
Attribute ReplacePic.VB_Description = "查找FindStr,并替换为PicFile所指向的图片文件,替换次数由time参数确定,为0时,替换所有"

'********************************************************************************
'    从Word.Range对象mysel中查找所有FindStr,并替换为PicFile图像
'          替换次数由time参数确定,为0时,替换所有
'********************************************************************************

If Len(C_PicFile) = 0 Then
    C_ErrMsg = 2
    Exit Function
End If

Dim i As Integer
Dim findtxt As Boolean

    mysel.Find.ClearFormatting
    mysel.Find.Replacement.ClearFormatting
    With mysel.Find
        .Text = FindStr
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
   mysel.HomeKey Unit:=wdStory
   findtxt = mysel.Find.Execute(Replace:=True)
   If Not findtxt Then
        ReplacePic = 0
        Exit Function
   End If
   i = 1
   Do While findtxt
        mysel.InlineShapes.AddPicture FileName:=C_PicFile
        If i = Time Then Exit Do
        i = i + 1
        mysel.HomeKey Unit:=wdStory
        findtxt = mysel.Find.Execute(Replace:=True)
   Loop
   ReplacePic = i
End Function

Public Function FindThis(FindStr As String) As Boolean
Attribute FindThis.VB_Description = "查找FindStr,如果模板中有FindStr则返回True"
If Len(FindStr) = 0 Then
    C_ErrMsg = 2
    Exit Function
End If
    mysel.Find.ClearFormatting
    mysel.Find.Replacement.ClearFormatting
    With mysel.Find
        .Text = FindStr
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
   mysel.HomeKey Unit:=wdStory
   FindThis = mysel.Find.Execute
End Function

Public Function ReplaceChar(FindStr As String, RepStr As String, Optional Time As Integer = 0) As Integer
Attribute ReplaceChar.VB_Description = "查找FindStr,并替换为RepStr,替换次数由time参数确定,为0时,替换所有"
'********************************************************************************
'     从Word.Range对象mysel中查找FindStr,并替换为RepStr
'          替换次数由time参数确定,为0时,替换所有
'********************************************************************************
Dim findtxt As Boolean

If Len(FindStr) = 0 Then
    C_ErrMsg = 2
    RaiseEvent HaveError
    Exit Function
End If

    mysel.Find.ClearFormatting
    mysel.Find.Replacement.ClearFormatting
    With mysel.Find
        .Text = FindStr
        .Replacement.Text = RepStr
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
  

 If Time > 0 Then
    For i = 1 To Time
         mysel.HomeKey Unit:=wdStory
         findtxt = mysel.Find.Execute(Replace:=wdReplaceOne)
         If Not findtxt Then Exit For
     Next
     If i = 1 And Not findtxt Then
         ReplaceChar = 0
     Else
        ReplaceChar = i
     End If
 Else
     mysel.Find.Execute Replace:=wdReplaceAll
 End If
End Function

 

Public Function GetPic(PicData() As Byte, FileName As String) As Boolean
Attribute GetPic.VB_Description = "把图像数据PicData,存为PicFile指定的文件"
'********************************************************************************
'     把图像数据PicData,存为PicFile指定的文件
'********************************************************************************
On Error Resume Next

If Len(FileName) = 0 Then
    C_ErrMsg = 2
    RaiseEvent HaveError
    Exit Function
End If

Open FileName For Binary As #1

If Err.Number <> 0 Then
    C_ErrMsg = 3
    Exit Function
End If

'二进制文件用Get,Put存放,读取数据
Put #1, , PicData
Close #1

C_PicFile = FileName
GetPic = True

End Function


Public Sub DeleteToEnd()
Attribute DeleteToEnd.VB_Description = "删除从当前位置到结尾的所有内容"
mysel.EndKey Unit:=wdStory, Extend:=wdExtend
mysel.Delete Unit:=wdCharacter, Count:=1
End Sub

Public Sub MoveEnd()
Attribute MoveEnd.VB_Description = "光标移动到文档结尾"
'光标移动到文档结尾
mysel.EndKey Unit:=wdStory
End Sub

Public Sub GotoLine(LineTime As Integer)
mysel.GoTo What:=wdGoToLine, Which:=wdGoToFirst, Count:=LineTime, Name:=""
End Sub

Public Sub OpenDoc(view As Boolean)
Attribute OpenDoc.VB_Description = "打开Word文件,View确定是否显示Word界面"
On Error Resume Next

'********************************************************************************
'     打开Word文件,并给全局变量mysel赋值
'********************************************************************************

If Len(C_TemplateDoc) = 0 Then
    mywdapp.Documents.Add
Else
    mywdapp.Documents.Open (C_TemplateDoc)
End If

    If Err.Number <> 0 Then
        C_ErrMsg = 4
        RaiseEvent HaveError
        Exit Sub
    End If
   
    mywdapp.Visible = view
    mywdapp.Activate
    Set mysel = mywdapp.Application.Selection
    'mysel.Select
   
End Sub

Public Sub OpenWord()
On Error Resume Next

'********************************************************************************
'     打开Word程序,并给全局变量mywdapp赋值
'********************************************************************************

    Set mywdapp = CreateObject("word.application")
    If Err.Number <> 0 Then
        C_ErrMsg = 1
        RaiseEvent HaveError
        Exit Sub
    End If
End Sub

Public Sub ViewDoc()
Attribute ViewDoc.VB_Description = "显示Word程序界面"
mywdapp.Visible = True
End Sub

Public Sub AddNewPage()
Attribute AddNewPage.VB_Description = "插入分页符"
mysel.InsertBreak Type:=wdPageBreak
End Sub

Public Sub WordCut()
Attribute WordCut.VB_Description = "剪切模板所有内容到剪切板"
    '保存模板页面内容
    mysel.WholeStory
    mysel.Cut
    mysel.HomeKey Unit:=wdStory
End Sub

Public Sub WordCopy()
Attribute WordCopy.VB_Description = "拷贝模板所有内容到剪切板"
    mysel.WholeStory
    mysel.Copy
    mysel.HomeKey Unit:=wdStory
End Sub

Public Sub WordDel()
    mysel.WholeStory
    mysel.Delete
    mysel.HomeKey Unit:=wdStory
End Sub

Public Sub WordPaste()
Attribute WordPaste.VB_Description = "拷贝剪切板内容到当前位置"
'插入模块内容
mysel.Paste
End Sub

Public Sub CloseDoc()
Attribute CloseDoc.VB_Description = "关闭Word文件模板"
'********************************************************************************
'     关闭Word文件模本
'********************************************************************************
On Error Resume Next


    mywdapp.ActiveDocument.Close False

If Err.Number <> 0 Then
    C_ErrMsg = 3
    Exit Sub
End If

End Sub

Public Sub QuitWord()
'********************************************************************************
'     关闭Word程序
'********************************************************************************
On Error Resume Next

    mywdapp.Quit
   
If Err.Number <> 0 Then
    C_ErrMsg = 3
    Exit Sub
End If
End Sub

Public Sub SavetoDoc()
Attribute SavetoDoc.VB_Description = "保存当前文档为FileName指定文件"
On Error Resume Next

'并另存为文件FileName

If Len(C_newDoc) = 0 Then
    C_ErrMsg = 2
    RaiseEvent HaveError
    Exit Sub
End If

    mywdapp.ActiveDocument.SaveAs (C_newDoc)
   
    If Err.Number <> 0 Then
        C_ErrMsg = 3
        RaiseEvent HaveError
        Exit Sub
    End If

End Sub


Public Property Get TemplateDoc() As String
Attribute TemplateDoc.VB_Description = "模板文件名."
TemplateDoc = C_TemplateDoc
End Property

Public Property Let TemplateDoc(ByVal vNewValue As String)
C_TemplateDoc = vNewValue
End Property

Public Property Get newdoc() As String
Attribute newdoc.VB_Description = "执行CloseDoc方法时,将模板文件另存为此文件名指定的新文件.如果不指定,在执行CloseDoc方法时,将产生一个错误"
newdoc = C_newDoc
End Property

Public Property Let newdoc(ByVal vNewValue As String)
C_newDoc = vNewValue
End Property

Public Property Get PicFile() As String
Attribute PicFile.VB_Description = "图像文件名"
PicFile = C_PicFile
End Property

Public Property Let PicFile(ByVal vNewValue As String)
C_PicFile = vNewValue
End Property

Public Property Get ErrMsg() As Integer
Attribute ErrMsg.VB_Description = "错误信息.ErrMsg代码: 1-word没有安装 2-缺少参数 3-没权限写文件 4-文件不存在"
ErrMsg = C_ErrMsg
End Property

要批量替换多个Word文档的同一内容,可以使用VB(Visual Basic)编程语言来自动化这个过程。下面是一个简单的代码示例: 1. 首先,需要创建一个新的VB项目。打开Visual Studio,选择VB项目模板。 2. 在VB代码编辑器中,引入Microsoft.Office.Interop.Word命名空间,这个命名空间提供了操作Word文档的功能。 3. 创建一个循环来遍历需要替换内容的所有Word文档。可以使用System.IO命名空间中的Directory.GetFiles方法获取指定目录下的所有Word文档。 4. 在循环中,使用Microsoft.Office.Interop.Word.Application和Document对象来打开每个Word文档。 5. 使用Document对象的Range.Find方法来查找需要替换内容。通过设置Find对象的Text属性为需要查找内容,设置Replacement对象的Text属性为替换后的内容。 6. 使用Find对象的Execute方法实施替换操作。 7. 最后,保存并关闭每个Word文档。 下面是示例代码: ``` Imports Microsoft.Office.Interop.Word Imports System.IO Module Module1 Sub Main() Dim docPath As String = "C:\YourDocs" ' Word文档所在的目录 Dim findText As String = "需要替换内容" Dim replaceText As String = "替换后的内容" Dim wordApp As New Application() Dim files As String() = Directory.GetFiles(docPath, "*.docx") ' 获取所有的Word文档 For Each file As String In files Dim doc As Document = wordApp.Documents.Open(file) Dim findRange As Range = doc.Content Dim replaceRange As Range = doc.Content With findRange.Find .Text = findText .Forward = True .Wrap = WdFindWrap.wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End With Do While findRange.Find.Execute() replaceRange.Text = replaceText replaceRange.Collapse(WdCollapseDirection.wdCollapseEnd) findRange.Collapse(WdCollapseDirection.wdCollapseEnd) Loop doc.Save() doc.Close() Next wordApp.Quit() End Sub End Module ``` 这段代码会遍历指定目录下的所有Word文档,并替换每个文档中的目标内容。请先替换代码中的“C:\YourDocs”为你的实际文档目录,并根据需求修改“findText”和“replaceText”变量的值。 以上就是使用VB实现批量替换多个Word文档的同一内容的基本步骤和示例代码。希望能对你有所帮助!
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值