Excel VBA – 将.xls附加到文件名以打开文件

我有代码打开一个具有可变date的文件,如下所示。 如果不在input框中inputmdyxls,此代码将不起作用。 我只想在input框中inputmdy。 请看一下,让我知道我失踪了。 谢谢!

Dim wbkOpen As Workbook Dim strFilePath As String Dim strFileName As String strFilePath = "D:\Users\stefan.bagnato\Desktop\Daily Performance Summary\Agent Group Daily Summary " strFileName = InputBox("Enter last Friday's date in the format MDY", "Friday's Date") Set wbkOpen = Workbooks.Open(strFilePath & strFileName, False, True) 

这是基本的string联合:

 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) 

理想情况下,您可以避免用户input(容易出错):

 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), "mdyy") 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) 

当然,允许用户手动select文件可能最终需要额外的validation和/或error handling(即,如果他们select了错误的文件呢?程序如何知道哪个date正确的date[我敢打赌它如果没有做一个丑陋的powershell循环,仍然会产生大量的假设,而这些循环可能并不总是持有)如果他们selectPDF或PPT文件而不是XLS等,但是这些点完全超出了范围这个问题。)

如果你有其他的后续,请按照适当的网站礼仪,并提出一个新的问题:)