您可以使用 VBA 中的DateAdd 函数减去一天,如下所示:
sFilename = "\\y:cash " & Format(DateAdd("d", -1, Date), "dd") & Format(Date, "mm") & Right(Year(Date), 2) & ".xlsx"
而且你不需要 CStr 函数,因为 format 和 right 函数已经返回字符串。
但是这个月的第一天呢?
这样做会更好:
sFilename = "\\y:cash " & Format(DateAdd("d", -1, Date), "ddmmyy") & ".xlsx"
或者,如果没有找到文件,您可以使用一个函数返回一个空字符串,或者根据您的条件返回最新文件的文件名,如下所示:
Public Function GetMostRecentFileByDate(dtStart As Date, sPath As String, sPrefix As String, sExt As String, sFormat As String) As String
Dim nDay As Integer
Dim sFilename As String
Dim dtDate As Date
Dim sFull As String
dtDate = dtStart
For nDay = -1 To -7 Step -1
sFilename = sPrefix & Format(dtDate, sFormat) & "." & sExt
sFull = sPath & "\" & sFilename
If Dir(sFull) <> "" Then
GetMostRecentFileByDate = sFull
Exit Function
End If
dtDate = DateAdd("d", -1, dtDate)
Next
End Function
用法:
sFullName = GetMostRecentFileByDate("03 Sept 2019", "\\y:", "cash ", "xlsx", "ddmmyy")
If sFullName <> "" Then
' Do Something With It
End If