用VBA在Word中,从文件2查找内容到文件1

想要实现的目标:

完成后的效果:

添加查找不到的处理:

VBA代码:

Sub 从文件2查找内容至文件1()
    t = Timer
    Dim 文件1 As Document, 文件2 As Document
    Set 文件1 = ActiveDocument
    Dim arr, brr
    Dim i As Integer
    
    Selection.HomeKey Unit:=wdStory, Extend:=wdMove '回到文档的起点
    
    ReDim arr(1 To ActiveDocument.Paragraphs.count)
    ReDim brr(1 To ActiveDocument.Paragraphs.count)
    For Each para In ActiveDocument.Paragraphs
        ' 处理段落的操作
        i = i + 1
        arr(i) = para.Range.text
    Next para
    
    ' 将焦点返回到之前的文档
'    遍历段落
    Documents.Open FileName:="J:\学习\1 书籍PDF\1 书籍PDF\办公自动化\VBA\我的VBA\练手VBA\从文件2查找内容至文件1\文件2.docx", ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=True, PasswordDocument:="", PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", WritePasswordTemplate:="", Format:=0, Encoding:=0, Visible:=True, OpenAndRepair:=False, DocumentDirection:=0, NoEncodingDialog:=True
    Set 文件2 = ActiveDocument
        ' 遍历段落
    文件2.Activate
    i = 1
    For Each a In arr
        '查找
        If 查找2(Left(a, Len(a) - 1), 1, 1) Then
            brr(i) = Selection.Paragraphs(1).Range.text
        Else
            brr(i) = "=:未找到" & vbCrLf
        End If
        i = i + 1
    Next
    文件2.Close
    文件1.Activate
    
    i = 0
    For Each para In ActiveDocument.Paragraphs
        ' 处理段落的操作
        i = i + 1
        para.Range.text = Left(para.Range.text, 1) & Right(brr(i), Len(brr(i)) - 1)
    Next para
    
    Set 文件1 = Nothing
    Set 文件2 = Nothing
    MsgBox "运行时间(秒):" & Timer - t
End Sub
Function 查找2(文本, 通配符, 向下)
    Dim rng As Range
    Selection.Find.ClearFormatting
    With Selection.Find
        .text = 文本
        .Forward = 向下
        .Wrap = wdFindContinue '往复查找
        .MatchWildcards = 通配符
        .Execute
    查找2 = .Found
        .Parent.Select
    End With
End Function

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值