从单元格中按名称搜索并打开Word文件

时间:2018-06-02 17:30:04

标签: vba excel-vba excel

我有代码搜索并打开一个Word文件,其名称与单元格中的值相同(“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

如何修改此代码,使其获取一个值来搜索不是来自特定单元格的文件,但检查整个列“B”,如果它找不到具有相同单元名称的文件,则通知没有这样的文件。

有人可以帮我这些吗?感谢。

1 个答案:

答案 0 :(得分:0)

请尝试以下操作。

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