我有一行代码根据指定的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个星期,例如(三月的最后一周-到五月的第一周)
是否有一种简便的方法来更新我的代码,使其仅引用保存在我指定的文件路径中的最近月份?
您必须扫描目录中的所有文件以找到最新的文件
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