我对VBA很新,在我的代码中,我正在通过文件路径打开最新文件,但我似乎得到了一个无限循环。对于上下文,工作簿每月只生成两次,因此我试图从当天开始反向。任何建议将不胜感激
Dim strToday As String
Dim strFileName_CBM As String
Dim b As Integer
'Selecting the correct reporting date
strToday = Format((Now()), "YYYY-MM-DD")
b = 0
strFileName_CBM = "\Administration\Finance\Reports\Portfolio\Current_Book_Monthly_" & _
Format(CDate(strToday) - b, "YYYY-MM-DD") & ".xlsx"
Do While Dir(strFileName_CBM) = ""
If Dir(strFileName_CBM) = "" Then
strFileName_CBM = "\Administration\Finance\Reports\Portfolio\Current_Book_Monthly_" & _
Format(CDate(strToday) - b, "YYYY-MM-DD") & ".xlsx"
End If
b = b - 1
Loop
答案 0 :(得分:1)
这样的事情(虽然你的路径看起来有点不完整......)
Sub Tester()
Const MAX_PERIOD As Long = 100
Dim b As Long
b = 0
'look back up to 100 days
Do While Len(Dir(FileName(Date - b))) = 0 And b < MAX_PERIOD
'Debug.Print FileName(Date - b)
b = b + 1
Loop
If b = MAX_PERIOD Then
'no file found
MsgBox "No file found newer than " & MAX_PERIOD & " days"
Else
'open the file
Workbooks.Open FileName(Date - b)
End If
End Sub
'construct file path & name from date
Function FileName(dt)
FileName = "\Administration\Finance\Reports\Portfolio\Current_Book_Monthly_" & _
Format(dt, "YYYY-MM-DD") & ".xlsx"
End Function