【问题标题】:how to open file with yesterday's workday in title如何打开标题为昨天工作日的文件
【发布时间】:2019-09-04 02:31:14
【问题描述】:

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

例如,今天星期一(9 月 2 日),打开星期五(8 月 30 日)的电子表格。

电子表格标题如下——“cash 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")

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

【问题讨论】:

  • 您可以使用WorksheetFunction.WorkDay 获取上一个工作日。可能有更好的使用示例,但这里是 one question 可能会有所帮助。

标签: excel vba


【解决方案1】:

您可以使用 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

【讨论】:

  • 这在工作日有效吗?例如 Monday-1 是上周五
  • 假设每个人周一到周五都在工作,但不是每个人都这样做。
  • 理想情况下,我会将 -1 设为在循环中减小的变量以确定要检查的文件名,然后返回 7 天。这将找到“最近工作的前一天”文件(如果存在)。检查昨天,如果找到,使用它,如果没有找到,检查前一天的文件......等等......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2017-08-22
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多