VBA Dialogue FileFilter Partial File Name

前端 未结 3 1308
北荒
北荒 2021-01-19 04:53

I have a directory with several .txt files. Let\'s say

hi.txt
hello.txt
hello_test.txt
test.txt

Using a file dialogue in VBA, how can I fil

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-19 05:36

    Is this what you are trying? Paste this in a module and run the sub OpenMyFile

    Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _
    "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
    
    Private Type OPENFILENAME
        lStructSize       As Long
        hwndOwner         As Long
        hInstance         As Long
        lpstrFilter       As String
        lpstrCustomFilter As String
        nMaxCustFilter    As Long
        nFilterIndex      As Long
        lpstrFile         As String
        nMaxFile          As Long
        lpstrFileTitle    As String
        nMaxFileTitle     As Long
        lpstrInitialDir   As String
        lpstrTitle        As String
        flags             As Long
        nFileOffset       As Integer
        nFileExtension    As Integer
        lpstrDefExt       As String
        lCustData         As Long
        lpfnHook          As Long
        lpTemplateName    As String
    End Type
    
    Sub OpenMyFile()
        Dim OpenFile As OPENFILENAME
        Dim lReturn As Long
        Dim strFilter As String
    
        OpenFile.lStructSize = Len(OpenFile)
    
        '~~> Define your filter here
        strFilter = "Text File (*test.txt)" & Chr(0) & "*test.txt" & Chr(0)
    
        With OpenFile
            .lpstrFilter = strFilter
            .nFilterIndex = 1
            .lpstrFile = String(257, 0)
            .nMaxFile = Len(.lpstrFile) - 1
            .lpstrFileTitle = .lpstrFile
            .nMaxFileTitle = .nMaxFile
            .lpstrInitialDir = "C:\Users\Siddharth Rout\Desktop\"
            .lpstrTitle = "My FileFilter Open"
            .flags = 0
        End With
    
        lReturn = GetOpenFileName(OpenFile)
    
        If lReturn = 0 Then
            '~~> User cancelled
            MsgBox "User cancelled"
        Else
            MsgBox "User selected" & ":=" & OpenFile.lpstrFile
            '
            '~~> Rest of your code
            '
        End If
    End Sub
    

提交回复
热议问题