我编写了一个将 5 个文件导入 Excel 工作簿的过程。如果在目录中找不到文件,则会弹出 OpenFileDialog 以允许用户浏览文件。如果用户选择的文件不是应该导入的文件,则会弹出警告。由于用户可能多次选择错误的文件,因此我编写了一个 While 循环来继续检查正确的文件名。
到那里一切都运作良好。这就是问题所在,如果文件不在预期的目录中,比如在 CD 上,用户浏览并找到正确的文件,并尝试打开它,我仍然收到文件不在的错误消息正确的。我知道为什么,While 循环是正确的,但我设置变量的方式是问题所在。
我的文件应该与我的工作簿位于同一路径中,因此我将变量设置如下:
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim strImportFile As String
strImportFile = xlWBPath & "\" & GetImportFiles(n)
但是因为我丢失的文件可能位于不同的目录中,所以我的变量strImportFile
不再有效,我现在必须获取所选文件的新路径并更改或声明一个新变量。我试图在我的代码上这样做,但它不起作用。下面是我的代码,我突出显示了有问题的区域:
Dim xlDestSheet As Excel.Worksheet
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim strImportFile As String
Dim xlWBSource As Object = Nothing
Dim xlWBImport As Object = Nothing
'Loop through the 5 sheets and files
For n As Long = 1 To 5 Step 1
strImportFile = xlWBPath & "\" & GetImportFiles(n)
xlDestSheet = DataSheets(n)
'Convert the indexed sheet name to a string
'so that it can be passed through the xlWB.Worksheets paramater
Dim strDestSheetName As String = xlDestSheet.Name
'If the file is found, then import, copy and paste the
'data into the corresponding sheets
If Len(Dir(strImportFile)) > 0 Then
xlWBSource = Globals.ThisWorkbook.Application.ActiveWorkbook
xlWBImport = Globals.ThisWorkbook.Application.Workbooks.Open(strImportFile)
xlWBImport.Worksheets(1).Cells.Copy(xlWB.Worksheets(strDestSheetName).Range("A1"))
xlWBImport.Close()
Else
'If a sheet is missing, prompt the user if they
'want to browse for the file.
'Messagbox variables
Dim msbProceed As MsgBoxResult
Dim strVmbProceedResults As String = ("Procedure Canceled. Your project will now close")
Dim strPrompt As String = " source file does not exist." & vbNewLine & _
"Press OK to browse for the file or CANCEL to quit"
'If the user does not want to browse, then close the workbook, no changes saved.
msbProceed = MsgBox("The " & GetImportFiles(n) & strPrompt, MsgBoxStyle.OkCancel + MsgBoxStyle.Question, "Verify Source File")
If msbProceed = MsgBoxResult.Cancel Then
msbProceed = MsgBox(strVmbProceedResults, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical)
xlWB.Close(SaveChanges:=False)
Exit Sub
Else
'If the user does want to browse, then open the File Dialog
'box for the user to browse for the file
'Open Fil Dialog box variable and settings
Dim ofdGetOpenFileName As New OpenFileDialog()
ofdGetOpenFileName.Title = "Open File " & GetImportFiles(n)
ofdGetOpenFileName.InitialDirectory = xlWBPath
ofdGetOpenFileName.Filter = "Excel Files (*.xls;*.xlsx; *.xlsm; *.csv)| *.xls; *.csv; *.xlsx; *.xlsm"
ofdGetOpenFileName.FilterIndex = 2
ofdGetOpenFileName.RestoreDirectory = True
'If the user presses Cancel on the box, warn that no
'file has been selected and the workbook will close
If ofdGetOpenFileName.ShowDialog() = System.Windows.Forms.DialogResult.Cancel Then
'Message box variables
Dim msbContinue As MsgBoxResult
Dim strAlert As String = ("You have not selected a workbook. The project will now close without saving changes")
'Once the user presses OK, close the file and do not save changes
msbContinue = MsgBox(strAlert, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "No Workbook Selected")
xlWB.Close(SaveChanges:=False)
Exit Sub
Else
'If the user does select the file, then import the file
'make sure the right file was selected, if the wrong file is selected, issue warning
While strImportFile <> GetImportFiles(n)
Dim msbContinue As MsgBoxResult
Dim strAlert As String = ("The selected file is invalid. Please select file: " & GetImportFiles(n) & vbNewLine & _
" to continue.")
msbContinue = MsgBox(strAlert, MsgBoxStyle.RetryCancel + MsgBoxStyle.Critical, "Wrong File Selection")
If msbContinue = MsgBoxResult.Cancel Then
xlWB.Close(SaveChanges:=False)
Exit Sub
Else
ofdGetOpenFileName.ShowDialog()
'*****Here is where I try to change the value of my
'*****variable, but my loop still does not break.
Dim strGetPath As String = Nothing
strGetPath = System.IO.Path.GetDirectoryName(ofdGetOpenFileName.FileName)
strImportFile = strGetPath & "\" & GetImportFiles(n)
End If
Continue While
If strImportFile = GetImportFiles(n) Then
Exit While
strImportFile = ofdGetOpenFileName.FileName
xlWBImport = Globals.ThisWorkbook.Application.Workbooks.Open(strImportFile)
xlWBImport.Worksheets(1).Cells.Copy(xlWB.Worksheets(strDestSheetName).Range("A1"))
xlWBImport.Close()
End If
Try
'Import the remainder of the files
xlWBSource = Globals.ThisWorkbook.Application.ActiveWorkbook
xlWBImport = Globals.ThisWorkbook.Application.Workbooks.Open(strImportFile)
xlWBImport.Worksheets(1).Cells.Copy(xlWB.Worksheets(strDestSheetName).Range("A1"))
xlWBImport.Close()
Catch
MsgBox(Err.Description, MsgBoxStyle.Critical, "Unexpected Error")
End Try
End While
End If
End If
End If
Next
End Sub