VBA对话框文件过滤器部分文件名

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 中选择。

3个回答

13

我看到你对于将文本放入文件名框有所顾虑,但这正是您需要做的事情,并且在您的情况下似乎是常规做法。我曾经也因为同样的问题卡住了。

这是我使用的方法:

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

谢谢,这正是我想要做的 - 奇怪的是实现这个过程的方式(??)。您可以通过“initialFileName”筛选器设置筛选器... 我猜只要它能工作就行 :-) - enderland

3

这并不过滤显示哪些文件,而是将文本放入文本框的“文本区域”。 - enderland

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接