简体   繁体   中英

Search and open a Word file by name from the cell

I have code that searches for and opens a Word file with the same name that value from the cell ("B9"):

Sub find()
    Dim f As String, folder As String, file_name As String
    Set wordapp = CreateObject("word.Application")
    folder = ThisWorkbook.Path & "\" 'Folder
    file_name = LCase(Range("B9")) & ".docx" 'Cell with file name
    f = Dir(folder)
    While Not Len(f) = 0
        If LCase(f) = file_name Then
            wordapp.documents.Open folder & f
            wordapp.Visible = True
            Exit Sub
        End If
        f = Dir()
    Wend
End Sub

How to modify this code so that it takes a value to search for a file not from a specific cell, but checks the entire column "B", if it does not find a file with the same cell name, then notifies that there is no such file.

Can someone help me with these? Thanks.

Try the following.

Sub find()
    Dim f As String, folder As String, file_name As String

    Set wordapp = CreateObject("word.Application")
    folder = ThisWorkbook.Path & "\" 'Folder
    f = Dir(folder)
    While Not Len(f) = 0
        If Not (IsError(Application.VLookup(LCase(f), Worksheets("Sheet1").Range("B:B"), 1, True))) Then
            wordapp.documents.Open folder & f
            wordapp.Visible = True
            Exit Sub
        End If
        f = Dir()
    Wend
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM