其中dd-mm-yy
代表运行报表的年月日。
我尝试了下面的代码,但这似乎无法找到该文件。
有人可以帮我改写以下代码-非常感谢。
Sub OpenLatest()
a matching date
Dim dtTestDate As Date
Dim sStartWB As String
Const sPath As String = "C:\Users\Documents\Weekly Contract Values Analysis\"
Const dtEarliest = #1/1/2018#
dtTestDate = Date
sStartWB = ActiveWorkbook.Name
While ActiveWorkbook.Name = sStartWB And dtTestDate >= dtEarliest
On Error Resume Next
Workbooks.Open sPath & "Contract Values UK - " & Format(dtTestDate, "(DD-MM-YY)") & ".xlsm"
dtTestDate = dtTestDate - 1
On Error GoTo 0
Wend
If ActiveWorkbook.Name = sStartWB Then MsgBox "Earlier file not found."
End Sub
答案 0 :(得分:1)
这是您要尝试的吗? (未经测试)
我假设文件名类似于Contract Values UK - dd-mm-yy.xlsm
Const sPath As String = "C:\Users\Documents\Weekly Contract Values Analysis\"
Const dtEarliest = #1/1/2018#
Sub Sample()
Dim i As Long
Dim dt As Date: dt = Date
Dim flName As String, dtPart As String
'~~> Loop through dates in reverse
For i = dt To dtEarliest Step -1
dtPart = Format(i, "dd-mm-yy")
'~~> Create your file name
flName = "Contract Values UK - " & dtPart & ".xlsm"
'~~> Check if exists
If Dir(sPath & flName) <> "" Then
MsgBox sPath & flName '<~~ You can now work with this file
Exit For
End If
Next i
End Sub