我如何在最近一个会计月之前打开文件?

问题描述 投票:0回答:1

我有一行代码根据指定的dt字符串打开工作簿。

Const filename = "Labor_Data_"
Const basepath = "C:\Users\CDL File"
Dim wbPreviousData as workbook
Dim dt As String: dt = Format(DateAdd("m", -1, Now), "mm_yyyy")

然后我用以下命令打开前几个月的文件:

Set wbPreviousData = Workbooks.Open(basepath & "\" & filename & dt & ".xlsx")

但是我意识到我公司的财务日历有时可以跨越5个星期,例如(三月的最后一周-到五月的第一周)

是否有一种简便的方法来更新我的代码,使其仅引用保存在我指定的文件路径中的最近月份?

excel vba
1个回答
0
投票

您必须扫描目录中的所有文件以找到最新的文件


Sub findlatest()

    Const filename = "Labor_Data_"
    Const basepath = "C:\Users\CDL File"

    Dim file As String, absfile As String
    Dim latest As String, ts As Double, tsmax As Double

    file = Dir(basepath & "\" & filename * "*")
    Do While Len(file) > 0

       ' check timestamp
       absfile = basepath & "\" & file
       ts = CDbl(FileDateTime(absfile))

       If ts > tsmax Then
          tsmax = ts
          latest = file
       End If

       file = Dir
    Loop

    Debug.Print latest

End Sub

© www.soinside.com 2019 - 2024. All rights reserved.