如何在VBA中重新抛出错误

时间:2016-10-25 21:48:05

标签: excel vba excel-vba

如果出现错误,我想做一些清理,然后让错误流动,以便全局处理。

在C#中我会做try finally,但这对于VBA是不可能的,只有On Eror GoTo <mylabel>

如何在标签中找到错误地重新抛出错误?

是否只能使用所有属性再次调用Err.Raise,不存在throw类关键字?:

Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext

2 个答案:

答案 0 :(得分:1)

这是正确的方法,但是不,您不必重新声明所有err属性。这些值将保留:

err.raise Err.Number

相同
Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext

https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/raise-method

如果不使用类模块,可能会更加复杂。默认情况下,将捕获并重新创建类模块的err对象,因此根据其声明方式,可以替换属性。

答案 1 :(得分:0)

我认为您应该使用ON ERROR GOTO ...

并继续在“ next_step”中进行错误处理

例如:

Dim iCounter
Dim sAttachment
Dim objAttachments

Set objAttachments = CreateObject("System.Collections.ArrayList")

objAttachments.Add "File 1.csv"
objAttachments.Add "File 2.csv"
objAttachments.Add "File 3.csv"

Set objFSO = CreateObject("Scripting.FileSystemObject")

strSMTP = "smtp.telenor.no"
strSubject = "Files form me to you"
strSubject = "XXXXX"
strSubject = "XXXX"
strBody = "XXXXXX"

' Create message and configuration
Set objMessage = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")

objConf.Load -1    ' CDO Source Defaults
Set objFields = objConf.Fields

With objFields
    .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTP
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    .Update
End With

' Initalize message
With objMessage
    Set .Configuration = objConf
    .To = "XXXX"
    .CC = ""
    .BCC = ""
    .From = "XXXX"
    .Subject = strSubject
    .TextBody = strBody
End With

' Add attachments
For iCounter = 1 To objAttachments.Count
    sAttachment = objAttachments.Item(iCounter - 1)
    If objFSO.FileExists(sAttachment) Then objMessage.AddAttachment sAttachment
Next

' Send Message
objMessage.Send