So instead of waiting for errors or trying to suppress them better check if the file exists. Therefore you can use a function like this, which returns true
if a file exists:
Public Function FileExists(FilePath As String) As Boolean
Dim Path As String
On Error Resume Next
Path = Dir(FilePath)
On Error GoTo 0
If Path <> vbNullString Then FileExists = True
End Function
For adding attachments I recommend to use an array for the file names, so you can easily loop through and attach the files if they exist. Everytime we add an attachment we increase the AttachedFilesCount
too.
This way you don't use On Error Resume Next
wrong and you don't run into debug issues because of that. So you have a clean solution.
With OutMail
.To = Cells(X, 4)
.CC = Cells(X, 6)
.Subject = Cells(X, 8)
.Body = Cells(1, 8)
Dim FileLocations As Variant
FileLocations = Array("C:UsersHKhanDesktopFinal Macro" & Cells(X, 1) & "-OICR.xlsx", _
"C:UsersHKhanDesktopFinal Macro" & Cells(X, 1) & "-OICLR.xlsx", _
"C:UsersHKhanDesktopFinal Macro" & "OIC - Bank Details" & ".pdf", _
"C:UsersHKhanDesktopFinal Macro" & "OICL - Bank Details" & ".pdf")
Dim AttachedFilesCount As Long
Dim FileLocation As Variant
For Each FileLocation In FileLocations
If FileExists(FileLocation) Then
.Attachments.Add (FileLocation)
AttachedFilesCount = AttachedFilesCount + 1
End If
Next FileLocation
If AttachedFilesCount > 0 Then
.Display 'display or send email
Else
.Close 'close it if no attachments
End If
End With
If you now still need additional error handling on adding the attachments (personally I don't think you need it necessarily) you can implement it like this:
On Error Resume Next 'turn error reporting off
.Attachments.Add (FileLocation) 'the line where an error might possibly occur.
If Err.Number <> 0 Then 'throw a msgbox if there is an error
MsgBox "Could not attach file """ & FileLocation & """ to the email." & vbCrLf & Err.Description, vbExclamation, "Error " & Err.Number, Err.HelpFile, Err.HelpContext
End If
On Error Goto 0 'turn error reporting on again!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…