Excel VBA 检查文件是否存在

Excel VBA check if file exists with a twist

这个话题很难具体和简短,但我尽力了:

假设我们在特定位置有一个文件夹,我们在其中获取名称为 let's use x1 的文件; x2; x3 等等

然后我们有一个 excel 文件,其中一列有数字。前任。 1; 2; 3;等等

我写了一个脚本,可以点击这些数字,这样一个资源管理器 window 就会弹出来搜索文件夹中的特定数字。

例如,我们点击数字“2”,然后会弹出一个资源管理器 window,其中包含在该特定文件夹中搜索“2x”的结果。

脚本如下所示:

Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)

Dim c As String
Dim backup As String

c = Target.Range
backup = "~%3D" & Left(c, 7)

    If Left(c, 1) = "C" And Len(c) > 7 And Right(c, 1) = "$" Then 'this part doesn't really matter
    RetVal = Shell("c:\Windows\explorer.exe ""search-ms:displayname=Search%20Results&crumb=System.Generic.String%3A" & backup & "%20kind%3A%3Dfolder&crumb=location:%5C%5Cserver%5Cbackup$", vbNormalFocus)

    End If

End Sub

我想知道是否有可能以某种方式查明是否存在与搜索相匹配的文件或者该文件不存在。我的意思是,例如,如果我单击 excel 中的数字“2”,资源管理器将弹出并显示名称包含 "x2" 的文件,或者它会显示“没有项目符合您的搜索。"

如果我们有搜索结果 我们没有,我想 return 以某种方式 excel 。 即使是布尔值也能为我解决问题。

我不能使用像这样的普通支票:

If Dir(folder) = "" Then

因为我们可以有多个同名文件,并且它们的名称包含创建日期。前任。 x1_02_04_2015 我们也可以有一个 x1_05_11_2014

提前致谢!

您可以尝试以下方法。您真的不需要使用任何 shell 功能

     Sub LoopThroughFilesWorkbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
        Dim MyObj As Object, MySource As Object, file As Variant, myBool As Boolean
        file = Dir("c:\testfolder\")
        Do While file <> ""
            Bool = False
            If InStr(file, "test") > 0 Then ' you can change teh condition here to fit your criteria
               myBool = True
               MsgBox ("Found" & file)
            End If
            file = Dir
        Loop
        If Not myBool Then
            MsgBox ("File not found")
        End If
    End Sub