如何以标题为昨天的工作日打开文件

时间:2019-09-04 02:31:14

标签: excel vba

我需要打开一个标题为昨天工作日的文件,而我不知道该怎么做。

例如今天(星期一)(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")

它将正确打开前一个工作日的电子表格

1 个答案:

答案 0 :(得分:0)

您可以在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