用文件中最新的日期名称打开一个Excel文件

时间:2019-01-22 10:42:52

标签: excel vba

enter image description here我每天运行一个名为“英国合同价值-dd-mm-yy”的报告

其中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

1 个答案:

答案 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