這是基本的字符串連接:
strFilePath & strFileName & ".xls"
你或許應該檢查以確保該文件存在,否則會出現錯誤:
Dim fullFileName As String
strFilePath & strFileName & ".xls"
If Dir(fullFileName) = "" Then
MsgBox "Invalid filename!"
Exit Sub
End If
Set wbkOpen = Workbooks.Open(fullFileName, False, True)
理想情況下,你能避免用戶 - 輸入(這是容易出錯)共:
Const strFilePath As String = "D:\Users\stefan.bagnato\Desktop\Daily Performance Summary\Agent Group Daily Summary "
Dim wbkOpen As Workbook
Dim LastFridayDate As String
Dim fullFileName As String
Dim fdlg as FileDialog
LastFridayDate = Format(Date - (Weekday(Date, vbFriday) - 1), "m.d.yy")
fullFileName = strFilePath & LastFridayDate & ".xls"
If Dir(fullFileName) = "" Then
If MsgBox("The file named " & fullFileName & " doesn't exist. Would you like to manually locate the file?", vbYesNo) = vbNo Then
Exit Sub
Else
Set fdlg = Application.FileDialog(msoFileDialogOpen)
'## Opens the fileDialog in the normal folder where these files should exist
fdlg.InitialFileName = strFilePath
'## Display the fileDialog to the user
fdlg.Show
'## Validate the fileDialog hasn't been canceled
If fdlg.SelectedItems.Count <> 0 Then
'## Return the value of the item selected by the user
fullFileName = fdlg.SelectedItems(1)
Else:
MsgBox "No file selected, exiting procedure..."
End If
End If
End If
Set wbkOpen = Workbooks.Open(fullFileName, False, True)
當然允許用戶手動選擇的文件最終可能需要額外的驗證和/或錯誤處理(即,如果他們選擇了錯誤的文件是什麼?程序如何知道哪些日期是正確日[我打賭它不能,沒有做一個醜陋的暴力循環仍使很多的假設可能並不總是抱着]如果他們選擇的PDF或一個PPT文件,而不是一個XLS等,但這些點是完全超出範圍了這個問題。)
如果您有其他跟進,請按照適當的場地禮儀和提出新問題:)
這將是罰款,如果該文件正在使用中,雖然application.displayalerts需要被禁用,以避免只讀對話。 – Zerk
謝謝David!該文件應該始終存在,所以唯一的問題是我會忘記日期。而不是做一個'退出小組',我怎麼能得到它回到輸入框? – sbagnato
使用'GoTo'語句或'While'循環。 –