简体   繁体   English

Excel VBA宏和错误消息

[英]Excel VBA macros and error messages

I'm very inexperienced in Excel and I'm running into a problem programming a macro. 我在Excel中经验不足,并且在编写宏时遇到问题。 It simply stops without any error dialog, no matter whether I set a breakpoint and step over or not. 不管我是否设置断点并跨步,它都将停止而没有任何错误对话框。

Am I missing something? 我想念什么吗? Do I have to turn on error messages explicitly? 我是否必须明确打开错误消息?

Something like this, in a module: 在模块中这样的事情:

Function Provoke(XYZ As Integer) As Integer
   Provoke = XYZ / 0
End Function

The Function is used in a formula inside of a cell, like this 像这样在单元格内部的公式中使用该函数

=Provoke(4711)

How can I make it complain about the division by zero? 我如何让它抱怨被零除?

If an error occurs in a Function when called from a worksheet as a UDF, you won't see any error messages- you just get a #VALUE error returned to the cell(s) 如果从工作表作为UDF调用时在Function中发生错误,您将看不到任何错误消息-您只会将#VALUE错误返回给单元格

If you call that same function from a Sub in VBA, you will see the error. 如果从VBA中的Sub调用相同的函数,则会看到错误。

If you want to be able to return more-specific error messages you'll need to to a little more coding. 如果您希望能够返回更具体的错误消息,则需要更多的编码。

Eg 例如

Function Provoke(XYZ As Integer)

   On Error GoTo haveError
   Provoke = XYZ / 0
   Exit Function

haveError:
    'what type of error did we get?
    Select Case Err.Number
        Case 11: Provoke = CVErr(xlErrDiv0)
        Case Else: Provoke = "Error!"
    End Select

End Function

A good reference for this: http://www.cpearson.com/excel/ReturningErrors.aspx 一个很好的参考: http : //www.cpearson.com/excel/ReturningErrors.aspx

Yes you need to make provision to tell VBA what to do if error occurs. 是的,您需要做好准备以告知VBA如果发生错误该怎么办。

The error is occuring because of this line in your code: 由于代码中的这一行而发生错误:

Provoke = XYZ / 0

No number is divisible by zero and it generates an error. 没有数字可被零整除,并且会产生错误。 Basic math: any number ÷ 0 = ∞ . 基本数学: any number ÷ 0 = ∞

To verify firsthand, you may try something like this to trap the error number as well as source and description: 为了直接进行验证,您可以尝试执行以下操作来捕获错误号以及来源和描述:

Function Provoke(XYZ As Integer)
    On Error Resume Next
    Provoke = XYZ / 0
    If Err.Number <> 0 Then Provoke = "Error# " & Err.Number & " - generated by " & Err.Source & " - " & Err.Description
    On Error GoTo 0
End Function

Now, if you try 现在,如果您尝试

=Provoke(4711)

You'll get the result like: 您将得到如下结果:

Error# 11 - generated by VBAProject - Division by zero

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM