vbawindowserror-handlingms-officemsgbox

How to get error message text which are sent by Runtime Engine


  1. Run the following macro.

     Sub Macro1()
         MsgBox "Hello"
     End Sub
    
  2. When the MsgBox pops up, press Ctrl+C keys on your keyboard.

  3. Open a NotePad file and press Ctrl+V keys on your keyboard.

  4. As you can see you are able to copy from MsgBox and paste into NotePad file.

  5. Now lets do second scenario.

  6. Run the following macro.

     Sub Macro2()
    
         Dim myNumber As Integer
         myNumber = 20
    
         Dim yourNumber As Integer
         yourNumber = 0
    
         'In mathematics, a number can not be divided by zero. So the following code must throw an error.
         Dim resultNumber As Integer
         resultNumber = myNumber / yourNumber
    
     End Sub
    
  7. When the MsgBox pops up, press Ctrl+C keys on your keyboard.

  8. Open a NotePad file and press Ctrl+V keys on your keyboard.

  9. As you can see you are NOT able to copy from MsgBox and paste into NotePad file.

My question: How to copy error messages which are sent by Runtime Engine to the Windows Clipboard as I give an example in the second scenario.


Solution

  • Well, you can copy a message from MsgBox, but in the second case, it is not a matter of a MsgBox. It is a message sent by compiler mentioning the error number and error description.

    To catch the respective data you should adapt your code in the next way (to place them in an ordinary MsgBox):

    Sub Macro234()
    
         Dim myNumber As Integer
         myNumber = 20
    
         Dim yourNumber As Integer
         yourNumber = 0
    
         'In mathematics, a number can not be divided by zero. So the following code must throw an error.
         Dim resultNumber As Integer
         On Error Resume Next
         resultNumber = myNumber / yourNumber
         If Err.number <> 0 Then
            MsgBox "Error number: " & Err.number & vbCrLf & " Error Description: " & Err.Description
         End If
         On Error GoTo 0
     End Sub
    

    The above code adaptation only answer your question as it has been formulated, but in the real life, with real needs, I cannot understand why the need of such an issue? Theoretically, you should use an error handling mechanism able to solve possible issues. You can use Err.Number to make the code to act in a suitable direction, according to it. For instance, If Err.Number = 5 then MsgBox "The denominator must be different of zero,,,": Exit sub.