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

时间:2015-08-05 18:25:51

标签: vba date filepath userform

我想打开一个最后有日期变量的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'

1 个答案:

答案 0 :(得分:0)

您可以使用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