How can i improve my function for handling alternative to Application.FileSearch VBA

后端 未结 4 2141
时光取名叫无心
时光取名叫无心 2020-12-16 08:56

I have decided to attempt a UDF around alternative to Application.FileSearch. I assume a few locations where a file COULD be located. Solutions on the internet tend to assum

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 09:31

    Option 1 - RecentFiles

    Although I have to agree with @TimWilliams' assessment that "long-winded" doesn't mean "inefficient", if the file is accessed frequently enough you should be able to find it in the .RecentFiles collection:

    Public Function FindFile() As String
        Dim x As Variant
        For Each x In Application.RecentFiles
            If x.Name Like "*File Name.xlsm" Then
                FindFile = x.Name
                Exit Function
            End If
        Next x
    End Function
    

    Keep in mind that this is a complete hack solution, and I would never use it for anything resembling production code, because the fall-back method if it fails would be similar to either what you posted or @tompreston's answer.


    Option 2 - WMI

    Again, this boils down to what your definition of "efficient" is. You can query the filesystem with WMI, but this is likely to be horrendously slow in processing time, especially if you don't have everything indexed:

    Public Function FindFile() As String
        With CreateObject("winmgmts:root/CIMV2")
            Dim results As Object, result As Object, query As String
            query = "SELECT TOP 1 * FROM Cim_DataFile WHERE Filename = 'File Name' AND Extension = 'xlsm'"
            Set results = .ExecQuery(query)
            For Each result In results
                FindFile = result.Path & "File Name.xlsm"
                Exit Function
            Next
        End With
    End Function
    

    You can probably speed this up by "suggesting" directories with an added query filter along the lines of "AND Path IN ('C:\X\X\', 'C:\X\X\X\')", but at that point you're better off with your original solution from the question.


    The correct answer is going to tend toward the "long winded", as that avoids having frustrated end users constantly contacting you when they get strange error dialogs because you chose terse coding over robust code. "Efficiency" isn't a just measure of how much you have to type. I'd consider a solution that I never have to provide support for or maintain incredibly efficient.

提交回复
热议问题