Error Handling
When working with macros in VBA it can be useful to catch any errors that either originate from COMSOL or from your own code. The VBA editor has settings that make it possible to catch errors in various ways. These are available in the Options window, which is accessible from the Tools menu of the VBA editor.
In the Options menu you can define the error handling settings on the General page, in the Error Trapping section:
Example
In the VBA editor enter the code below. The code starts a COMSOL Multiphysics server and connects it with Excel. Finally, it tries to load a model MPH file that does not exist, as it is meant to fail.
Sub loadfile_error()
 
Set ModelUtil = CreateObject("comsolcom.modelutil")
Set ComsolUtil = CreateObject("comsolcom.comsolutil")
Set RibbonUtil = ComsolUtil.GetRibbonUtil
 
Set model = RibbonUtil.OpenModel("c:\\foo.mph")
 
End Sub
Assuming that the file foo.mph does not exists and if the error trapping is set to Break on All Error, the following error message is returned:
The numbers do not have any useful meaning, but the message in the window states Failed to load model., which is expected. Click the End button to stop the VBA code from running.
When writing your own code, you may want to be able to handle errors differently so that you can show a nice dialog about the problem or perhaps fix the problem on the fly. This is especially useful if you write code that other people will use. The On Error statement allow you to handle any error that may occur.
Update the code above such as:
Sub loadfile_error()
 
On Error GoTo errorhandler
Set ModelUtil = CreateObject("comsolcom.modelutil")
Set ComsolUtil = CreateObject("comsolcom.comsolutil")
Set RibbonUtil = ComsolUtil.GetRibbonUtil
 
Set model = RibbonUtil.OpenModel("c:\\foo.mph")
Exit Sub
 
errorhandler:
Call MsgBox("Error: " + Err.Description)
End Sub
Make sure the Error trapping option is set to Break on Unhandled Errors and run the script. You will now get the following dialog:
In this example we are just showing an error message and an OK button. For more advanced error handling you may want to customize the error message further and provide different options to the user.