VBA 使用仅知道扩展名的通配符打开文件

VBA Open file with wildcard knowing only extension

我正在尝试让 Excel 打开给定文件夹中的任何文件 (ThisWorkbook.Path\Peach\Apple) 具有 .xlsm 扩展名(始终只有 1 个文件)。是否可以用通配符打开它?我不知道文件名,只知道扩展名。

如果不行,有什么办法吗?

尝试下面的代码,它将在您请求的路径中打开您的“*.xlsm”文件。

Sub OpenXLSMWildcardfile()

Dim Path As String

Path = ThisWorkbook.Path & "\Peach\Apple\"
Workbooks.Open (Path & "*.xlsm")

End Sub

只需向文件系统询问第一个匹配文件:

Dim path As String: path = ThisWorkbook.path & "\Peach\Apple\"

FindFirstFile = Dir$(path & "*.xlsm")

If (FindFirstFile <> "") Then 
   Workbooks.Open path & FindFirstFile
Else
   '// not found
End If

(这不会搜索子目录)

打开扩展名为(.xlsm)的宏文件所需代码的PFB。

Sub OpeningFile()

'Declaring variables
Dim FileName, FolderPath As String

'Initializing folder path
FolderPath = ThisWorkbook.Path & "\Peach\Apple\"

'Finding the file name using wildcard
FileName = Dir(FolderPath & "*.xlsm")

'Looping through the workbook which are saved as macro enabled workbooks
While FileName <> ""
    Workbooks.Open FolderPath & FileName
    FileName = Dir()
Wend

End Sub

您提到打开最后修改的文件或名称最短的文件会很好,所以让我们开始吧 - 有一个代码 示例 如何获取所有三个文件(最先发现、最后修改、名称最短)。您可以根据需要修改它(添加一些参数、添加错误处理、仅指定 return 等)。

Sub Test()
   'declarations
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Dim path As String

    Dim first_finded As Object
    Dim recently_modified As Object
    Dim shortest_name As Object
    Dim recently As Date
    Dim shortest As Long
    Dim firstFinded As Boolean

    'setting default recently date(24 hours from now) and path
    recently = DateAdd("h", -24, Now)
    path = ThisWorkbook.path & "\Peach\Apple\"

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(path)


    'iteration over folder
    For Each file In folder.Files
        If file.Name Like "*.xlsm" Then

            'grab first finded .xlsm
            If Not firstFinded Then
                firstFinded = Not firstFinded
                Set first_finded = file
            End If

            'grab lastmodified .xlsm
            If file.DateLastModified > recently Then
                recently = file.DateLastModified
                Set recently_modified = file
            End If

            'grab short named .xlsm
            If shortest = 0 Or shortest > Len(file.Name) Then
                shortest = Len(file.Name)
                Set shortest_name = file
            End If
        End If
    Next

    'debug-print names
    Debug.Print first_finded.Name
    Debug.Print recently_modified.Name
    Debug.Print shortest_name.Name

    'so now you can uncomment this and open what you want
    'Call Workbooks.Open(path & recently_modified.Name)

End Sub