我需要打开一个标题为昨天工作日的文件,但我不知道该怎么做。
例如,周一(9月2日)今天,打开周五(8月30日)的电子表格。
电子表格的标题如下-“现金300819”
我已经尝试了以下代码,但似乎不起作用
Dim wbO As Workbook, wbN As Workbook
Set wbO = ActiveWorkbook
Set wbN = Workbooks.Open("\\y:cash " & Format(CStr(Date)-1, "dd") & CStr(Format(Date, "mm")) & Right(CStr(Year(Date)), 4) & ".xlsx")
它将正确打开前一个工作日的电子表格
发布于 2019-09-04 10:41:48
您可以使用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
https://stackoverflow.com/questions/57780740
复制相似问题