使用具有日期变量的文件路径创建宏

Create a macro with a file path that has a date variable

我想打开一个 Excel 文件,该文件末尾有一个日期变量。到目前为止,我已经创建了一个好的代码来根据从当前日期向后工作来检索文件。我更喜欢用户表单或输入框来指定所需的确切日期。日期采用 ddmmyyyy 格式,位于文件名的末尾。非常感谢任何帮助。

Sub OpenLatest()
  ---Opens a sheet based on date, searches backward from today til it finds   a  matching date
Dim TestDate As Date
Dim StartWB As String

Const sPath As String = "C:\Users\Laurence\Documents\"
Const dtEarliest = #6/1/2015#  '--to stop loop if file not found by earliest valid date.

TestDate = Date
StartWB = ActiveWorkbook.Name

While ActiveWorkbook.Name = StartWB And TestDate >= dtEarliest
    On Error Resume Next
    Workbooks.Open sPath & "Firstmacro_dtetime1 " & Format(TestDate, "ddmmyyyy") & ".xlsx"
    TestDate = dtTestDate - 1
    On Error GoTo 0
Wend

If ActiveWorkbook.Name = sStartWB Then MsgBox "Earlier file not found."
End Sub'

您可以使用 InputBox() 函数向用户请求日期。

Dim strDate As String
strDate = InputBox("Enter a date:")

If Not IsDate(strDate) Then
    MsgBox "Not a date"
    Exit Sub
End If

' Create the file path...
Dim strPath As String
strPath = "C:\Users\Laurence\Documents\Firstmacro_dtetime1 " & Format$(strDate, "ddmmyyyy") & ".xlsx"

' Make sure it exists...
With CreateObject("Scripting.FileSystemObject")
    If .FileExists(strPath) Then
        Workbooks.Open strPath
    End If
End With