excel 使用VBA打开带有可变字符的文件

jc3wubiy  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(278)

我需要打开一系列的工作簿,其中有尾随字符,每天变化。
文件按以下约定命名:
文件名_YYYY_MM_DD_(随机尾随数字)
我做了大量的研究,只找到了与日期更改有关的答案。理想情况下,我希望能够围绕日期更改以及随机尾随字符的问题进行写作。

Sub openwb()

Dim sPath As String, sFile As String, sWild As String
Dim wb As Workbook

sPath = "the path where the file is located "
  sWild = sPath & "Name of the file"
    sFile = sPath & Dir(sWild)

Set wb = Workbooks.Open(sFile)

End Sub
gojuced7

gojuced71#

使用FormatDate和通配符*

sWild = sPath & Format(Date, "_yyyy_mm_dd_") & "*"
sFile = Dir(sWild)

If sFile <> vbNullString Then
   Set wb = Workbooks.Open(sPath & sFile)
End If
1tu0hz3e

1tu0hz3e2#

打开文件夹中的Excel文件

Sub OpenWorkbook()
    
    ' Define constants.
    
    Const SRC_FOLDER_PATH As String = "C:\Test"
    Const SRC_FILE_BASE_NAME As String = "*" ' adjust!
    Const SRC_DATE_PATTERN As String = "_YYYY_MM_DD_"
    Const SRC_TRAIL As String = "*"
    Const SRC_EXTENSION_PATTERN As String = ".xls*" ' adjust!
    
    ' Source Path
    
    Dim pSep As String: pSep = Application.PathSeparator
    Dim sPath As String: sPath = SRC_FOLDER_PATH
    If Right(sPath, 1) <> pSep Then sPath = sPath & pSep
    
    Dim sFolderName As String: sFolderName = Dir(sPath, vbDirectory)
    If Len(sFolderName) = 0 Then
        MsgBox "The path '" & sPath & "' was not found.", vbExclamation
        Exit Sub
    End If
    
    ' First Source File
    
    Dim sDate As Date: sDate = Date ' 'Date' for today; adjust!
    
    Dim sFilePattern As String: sFilePattern = SRC_FILE_BASE_NAME _
        & Format(sDate, SRC_DATE_PATTERN) & SRC_TRAIL & SRC_EXTENSION_PATTERN
    
    Dim sFileName As String: sFileName = Dir(sPath & sFilePattern)
    
    If Len(sFileName) = 0 Then
        MsgBox "No files matching the pattern '" _
            & sFilePattern & "' found in '" & sPath & ".", vbExclamation
        Exit Sub
    End If
    
    ' Loop
    
    Dim swb As Workbook ', sws As Worksheet, srg As Range

    Do While Len(sFileName) > 0
        
        ' Test with...
        Debug.Print sFileName
        
        'Set swb = Workbooks.Open(sPath & sFileName)
           
        ' code per each opened workbook...
           
        ' When reading...
        'swb.Close SaveChanges:=False
        sFileName = Dir ' next file
    Loop

    ' Inform.

    MsgBox "Done", vbInformation

End Sub

相关问题