VBA对话FileFilter部分文件名

时间:2012-05-18 19:34:19

标签: vba filesystems

我有一个包含几个.txt文件的目录。我们说

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

在VBA中使用文件对话框,如何过滤以在下拉列表中仅显示“* test.txt”匹配文件(即最后两个)?或者我只能使用*。过滤器?

以下似乎应该可行,但不会:

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

编辑:澄清如果不清楚:我想过滤“ test.txt”而不是“ .txt”文件,所以我只能从hello_test.txt和test.txt中选择在选择器中。

3 个答案:

答案 0 :(得分:11)

我发现您担心将文本放在文件名框中,但这正是您需要做的事情,并且似乎是您的情况的标准。我完全挂了同样的问题。

这就是我使用的:

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

答案 1 :(得分:3)

filedialog怎么样?

Dim dlgOpen As FileDialog
Set dlgOpen = Application.FileDialog(msoFileDialogOpen)
With dlgOpen
    .AllowMultiSelect = True
    .InitialFileName = "Z:\docs\*t*.*x*"
    .Show
End With

http://msdn.microsoft.com/en-us/library/aa213120(v=office.11).aspx

答案 2 :(得分:2)

这是你在尝试什么?将其粘贴到模块中并运行子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