Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Dialogue FileFilter Partial File Name

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 filter to show only "*test.txt" matching files (ie last two) in the dropdown? Or can I only use *. filters?

The following seems it should work but does not:

Sub TestIt()
   Dim test As Variant 'silly vba for not having a return type..
   test = Application.GetOpenFilename(FileFilter:="test (*test.txt), *test.txt")
End Sub

edit: clarifying in case this wasn't clear: I want to filter "test.txt" instead of ".txt" files so I can only select from hello_test.txt and test.txt in the chooser.

like image 247
enderland Avatar asked Dec 05 '22 16:12

enderland


1 Answers

I see that you are concerned about putting text in the file name box, but that is exactly what you need to do and appears to be the norm for your situation. I got hung up on the exact same issue.

This is what I used:

Public Sub Browse_Click()

Dim fileName As String
Dim result As Integer
Dim fs

With Application.FileDialog(msoFileDialogFilePicker)
    .Title = "Select Test File"
    .Filters.Add "Text File", "*.txt"
    .FilterIndex = 1
    .AllowMultiSelect = False
    .InitialFileName = "*test*.*"

    result = .Show

    If (result <> 0) Then
        fileName = Trim(.SelectedItems.Item(1))

        Me!txtFileLocation = fileName

    End If
End With
like image 136
Andy Levesque Avatar answered Dec 24 '22 22:12

Andy Levesque