There are two ways to handle an error in Excel VBA. Quick way is to use type
On Error Resume Next Just before the line where error is coming.
this will ignore all the errors.
However the best way is to use the Error handler to show the user the exact error.
Private Sub Btn_RunTime_ErrorHandling_Click()
Dim answer As Integer
Dim default_path As String
Dim SrcSheet As Excel.Worksheet
Dim Src_WB As Excel.Workbook
Dim sMyDir, sDocName As String
Dim sh As Worksheet
default_path = ThisWorkbook.Path & "\Extract"
If Dir(default_path & "\") = "" Then
MsgBox "No files in Folder ", vbCritical
Call Shell("explorer.exe " & default_path & "\", vbNormalFocus)
Exit Sub
End If
sMyDir = (default_path & "\")
sDocName = Dir(sMyDir)
While sDocName <> ""
If sDocName Like "*.xls*" Then 'IF XLS OR XLSX FILES ARE FOUND THEN OPEN THEM
Set Src_WB = Workbooks.Open(sMyDir & sDocName, ReadOnly:=True)
On Error GoTo ErrHandler:
Set SrcSheet = Src_WB.Sheets("Sheet1")
MsgBox sDocName
Src_WB.Close False 'CLOSING THE FILE
End If
sDocName = Dir() 'MOVING TO NEXT FILE
Wend
Application.ScreenUpdating = True
MsgBox "Done", vbInformation
Exit Sub
ErrHandler:
MsgBox Err.Number & "-" & Err.Description, vbCritical
End Sub
On Error Resume Next Just before the line where error is coming.
this will ignore all the errors.
However the best way is to use the Error handler to show the user the exact error.
Private Sub Btn_RunTime_ErrorHandling_Click()
Dim answer As Integer
Dim default_path As String
Dim SrcSheet As Excel.Worksheet
Dim Src_WB As Excel.Workbook
Dim sMyDir, sDocName As String
Dim sh As Worksheet
default_path = ThisWorkbook.Path & "\Extract"
If Dir(default_path & "\") = "" Then
MsgBox "No files in Folder ", vbCritical
Call Shell("explorer.exe " & default_path & "\", vbNormalFocus)
Exit Sub
End If
sMyDir = (default_path & "\")
sDocName = Dir(sMyDir)
While sDocName <> ""
If sDocName Like "*.xls*" Then 'IF XLS OR XLSX FILES ARE FOUND THEN OPEN THEM
Set Src_WB = Workbooks.Open(sMyDir & sDocName, ReadOnly:=True)
On Error GoTo ErrHandler:
Set SrcSheet = Src_WB.Sheets("Sheet1")
MsgBox sDocName
Src_WB.Close False 'CLOSING THE FILE
End If
sDocName = Dir() 'MOVING TO NEXT FILE
Wend
Application.ScreenUpdating = True
MsgBox "Done", vbInformation
Exit Sub
ErrHandler:
MsgBox Err.Number & "-" & Err.Description, vbCritical
End Sub
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.