You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为指定文件夹多文件搜索宏添加InputBox输入搜索词

修改VBA宏实现通过InputBox输入搜索词

原宏里的搜索词是固定写死的,要改成让用户通过InputBox输入、无需手动修改代码,只需做以下调整:

修改要点

  • 移除固定的搜索词常量定义,改用字符串变量接收用户输入
  • 添加输入校验逻辑,若用户取消输入或未填写内容,直接退出宏,避免后续报错

修改后的完整代码

Sub CollateDocumentData()
    Application.ScreenUpdating = False
    Dim strFolder As String, strFile As String, strDocNm As String, strTmp As String, strOut As String
    Dim wdDoc As Document, i As Long
    Dim strFnd As String ' 替换原常量为变量
    
    ' 通过InputBox获取用户输入的搜索词,多个词用逗号分隔
    strFnd = InputBox("请输入要搜索的词汇,多个词汇用逗号分隔:", "输入搜索词")
    ' 校验输入:若用户取消或输入为空,直接退出
    If strFnd = "" Then
        MsgBox "未输入搜索词,已退出操作。"
        Application.ScreenUpdating = True
        Exit Sub
    End If
    
    strDocNm = ActiveDocument.FullName
    strFolder = GetFolder: If strFolder = "" Then Exit Sub
    strFile = Dir(strFolder & "\*.doc", vbNormal)
    While strFile <> ""
      If strFolder & "\" & strFile <> strDocNm Then
        Set wdDoc = Documents.Open(FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
        strTmp = ""
        With wdDoc
          With .Range.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .MatchCase = False
            .MatchWholeWord = True
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            For i = 0 To UBound(Split(strFnd, ","))
              .Text = Split(strFnd, ",")(i)
              .Execute
              If .Found = True Then strTmp = strTmp & vbCr & "" & Split(strFnd, ",")(i)
            Next
          End With
          If strTmp <> "" Then strOut = strOut & vbCr & strFile & ": " & strTmp & Chr(13)
          .Close SaveChanges:=True
        End With
      End If
      strFile = Dir()
    Wend
    Set wdDoc = Nothing

    '如果要在新文档中显示结果,注释掉下面的MsgBox行,取消注释Documents.Add和ActiveDocument相关行
    'Documents.Add
    'ActiveDocument.Range.Text = "搜索结果如下:" & strOut
    MsgBox ("搜索结果如下:" & vbCr & strOut)
    Application.ScreenUpdating = True
End Sub

Function GetFolder() As String
    Dim oFolder As Object
    GetFolder = ""
    Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "选择目标文件夹", 0)
    If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
    Set oFolder = Nothing
End Function

说明

  • 运行宏后会先弹出输入框,提示用户输入要搜索的词汇,多个词汇用逗号分隔(比如输入合同,协议)
  • 若用户点击取消或未输入任何内容,宏会提示并退出,避免无效操作
  • 原宏的核心搜索逻辑保持不变,只是把固定搜索词换成了用户输入的内容

内容的提问来源于stack exchange,提问作者Luke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 16:57:45