Excel VBA - Assigning a might be not existing content to a variable

Dear Experts,

Actually writing a code with SAP scripting (a special scripting language for SAP application) in VBA and got to an issue, could you please advise in it?

I would like to assign a content to the variable ErrMes with the following line,

ErrMes = session.findById("wnd[2]/usr/txtMESSTXT1").Text

Open in new window


which is basically a message text on Window 2 in SAP application (wnd[2]), but that might not appear at all in certain scenarios.

Briefly the issue is that if that does not appear in the application then there is nothing to assign to the variable and the VBA code stops. Do you have idea eventually how to handle those exception cases?

Thanks in advance,
LVL 1
csehzIT consultantAsked:
Who is Participating?
 
MacroShadowConnect With a Mentor Commented:
That is what error handling or trapping is all about.
This is a simple example:

    On Error Goto ErrHandler:
    ErrMes = session.findById("wnd[2]/usr/txtMESSTXT1").Text ' may cause an error
    '
    ' more code 
    '
    ErrHandler:
    ' error handling code such as a message box notifying the user about the error
    Resume Next
    End Sub 

Open in new window


On Error Goto ErrHandler
tells the code to skip to the ErrHandler label when an error occurs.
The ErrHandler label (or whatever you choose to name it) is typically written as the last code block of a subroutine or function.
0
 
NorieConnect With a Mentor VBA ExpertCommented:
When the code stops do you get an error message?

How is ErrMes declared?

Have you considered something like this?
Set objMes = session.findById("wnd[2]/usr/txtMESSTXT1").Text

If obJMes Is Nothing Then ' message not found
    MsgBox "Message not found"
Else
   ErrMes = objMes.Text
End If

Open in new window

0
 
csehzIT consultantAuthor Commented:
Thank you for the answers
0
 
NorieVBA ExpertCommented:
Oops, my code was slightly incorrect.

Here's the corrected version.
Set objMes = session.findById("wnd[2]/usr/txtMESSTXT1")

If obJMes Is Nothing Then ' message not found
    MsgBox "Message not found"
Else
   ErrMes = objMes.Text
End If

Open in new window

0
All Courses

From novice to tech pro — start learning today.