4

我有一个包含几个 .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 中进行选择。

4

3 回答 3

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
于 2012-05-30T17:47:45.200 回答
3

文件对话框怎么样?

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

于 2012-05-18T19:51:33.593 回答
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
于 2012-05-18T21:34:14.057 回答