首页 文章

Excel VBA . 搜索工具

提问于
浏览
1

我是Excel VBA的初学者并且有一些问题 .

  • 我想根据用户输入(文件名)搜索指定的文件夹 . 我可以让那部分工作,但是,我希望它不仅仅搜索一种格式(.docx),还包括搜索.pdf和.doc .

Clarification:
G:\NEWFOLDER\NAMEFOLDER 下的文件夹包含扩展名为.doc,.docx和.pdf的文件,我想搜索整个文件夹并在 Sheet2 上报告回我的电子表格 .

Dim NAME As String
Dim File_Path As String
    NAME = InputBox(" Enter Your NAME (EX: JOHNP) ")
    File_Path = "G:\NEWFOLDER\NAMEFOLDER" & NAME & ".docx"

    If Dir(File_Path) <> "" Then
        ThisWorkbook.Sheets("Sheet2").Activate
        Range("D5") = ("Checked")
        Range("E5") = NAME
    Else
        MsgBox "NAME Not found"
    End If
End Sub
  • 如何在其中搜索文档?

Clarification:
上面的代码只告诉我用户输入是否位于编码路径内 . 我想要做的下一步是在该文档中搜索关键字并报告回电子表格 . 例如,在 JOHNP.doc 中有一列 age . 我希望代码使用"22"向 Sheet2 单元格报告 .

Is this even possible with word document search, or is it better if the JOHNP is in excel format?

1 回答

  • 0

    这应该对你有所帮助 - 这将循环遍历指定文件夹位置中的文件(如果存在),并且仅针对 .doc.docx.pdf .

    至于你的第二个问题 - 是的,你可以从你的文件中提取这个数字,但是,你每次都在同一个地方,那么这将是相当容易的 - 希望在一个 Table ,然后它会有一个明确的参考(如 ActiveDocument.Tables(1).Cells(1,1) 等 . 现在,下面的代码将遍历所有文件,当它找到第一个匹配时,它将为您打开word文档(然后退出循环) .

    Sub Test()
    Dim NAME As String
    Dim File_Path As String
    Dim StrFile As String
    
        NAME = InputBox(" Enter Your NAME (EX: JOHNP) ")
        File_Path = "G:\NEWFOLDER\NAMEFOLDER\" & NAME & "\"
    
        StrFile = Dir(File_Path)
    
        If Dir(File_Path) <> "" Then
            Do While Len(StrFile) > 0
                If InStr(StrFile, ".doc") > 0 Or _
                   InStr(StrFile, ".pdf") > 0 Then
                    Debug.Print StrFile
                    'ThisWorkbook.Sheets("Sheet2").Range("D5") = ("Checked")
                    'ThisWorkbook.Sheets("Sheet2").Range("E5") = NAME
    
                    If InStr(StrFile, ".doc") > 0 Then
                        Set wordapp = CreateObject("word.Application")
                        wordapp.documents.Open File_Path & StrFile
                        wordapp.Visible = True
                        Exit Do
                    End If
                End If
                StrFile = Dir
            Loop
        Else
            MsgBox NAME & " Not found"
        End If
    End Sub
    

相关问题