Question : Error handling stop routine on error

I am letting the user select an Excel file to import a spreadsheet into a table with the following code:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
Private Sub Command1_Click()
    On Error GoTo Error_Handler
    Dim fdg As FileDialog, vrtSelectedItem As Variant
    Dim strSelectedFile As String
    
    Set fdg = Application.FileDialog(msoFileDialogFilePicker)
    
    With fdg
        .AllowMultiSelect = False
        .InitialView = msoFileDialogViewDetails
        If .Show = -1 Then
            For Each vrtSelectedItem In .SelectedItems
            strSelectedFile = vrtSelectedItem
        Next vrtSelectedItem
        Else
        End If
        Dim StrSQL As String
        StrSQL = "Delete * from Scrap;"
        DoCmd.SetWarnings False
        DoCmd.RunSQL StrSQL
        DoCmd.SetWarnings True
        DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "Scrap", strSelectedFile, True, , False
        

        
        End With
        Set fd = Nothing
Exit_Procedure:
     Exit Sub
   
        
Error_Handler:
DisplayUnexpectedError Err.Number, Err.Description
        
End Sub



And the error handling code:
 
1:
2:
3:
4:
5:
6:
Public Sub DisplayUnexpectedError(ErrorNumber As String, ErrorDescription As String)
Select Case Err.Number
       Case 2522
          MsgBox "You did not select an Excel file"
       End Select
End Sub


If they choose cancel in the FileDialog window nothing gets imported and the table is left empty. I get the message box that I want, but the code continues and imports nothing into the table. How do I exit the code if the error occurs? I am new to VBA and even newer to error handling. Thanks for any help you can give me on this.

Answer : Error handling stop routine on error

try this


If  len(trim(strSelectedFile) & "") >0 Then
   Import Spreadsheet
Else
   msgbox
End If
Random Solutions  
 
programming4us programming4us