vbaerror-handlingscriptingsap-gui

Sent each SAP command to another sub and execute it for error handling


When a command is sent to SAP GUI like SAPsession.FindById("wnd[0]").resizeWorkingPane(170, 25, False) and an error occurs I'd like to log the error and let the script continue after user input (if needed) to fix the error. Next, I want to use the Log to examine the errors and fix them.

I was thinking to do this via an additional sub that handles the SAP GUI command and catches the error like below.

I know that the below code does not workout at all but it's just for illustration of what I'd like to accomplish.

Thanks!


  Private sub DoSomethingInSAP() 
      SAPCommand(SAPsession.FindById("wnd[0]").resizeWorkingPane(170, 25, False))
      SAPCommand(SAPsession.FindById("wnd[0]/tbar[0]/okcd").text = "/nsu3")
      SAPCommand(SAPsession.FindById("wnd[0]").sendVKey(0))
  End Sub

  Private sub SAPCommand(input as ?????)         '//SAPCommand to be executed
      try
           Run SAPCommand
      Catch ex as Exception
           Log("Error: " & input & vbCRLF & ex.tostring)
           msgbox("First fix the error for command: " & vbCRLF & input & vbCRLF & "Next: Click 'Ok' to continue")
      end try
  end sub

Solution

  • I would suggest something like the following:

    Private Sub DoSomethingInSAP()
       On Error GoTo error
    
       SAPsession.FindById("wnd[0]").resizeWorkingPane(170, 25, False)
       SAPsession.FindById("wnd[0]/tbar[0]/okcd").Text = "/nsu3"
       SAPsession.FindById("wnd[0]").sendVKey (0)
       
       Exit Sub
       
    error:
       Log("Error: " & input & vbCRLF & ex.tostring)
       MsgBox("First fix the error for command: " & vbCRLF & input & vbCRLF & "Next: Click 'Ok' to continue")
       
       Resume Next
    End Sub
    

    If an error occurs with the first FindById, control jumps to the error block where you can do logging and user input. The Resume Next is the key piece for your scenario. It will return control to the statement following the statement that threw the error, in this case the second FindById.

    One negative with this approach is you won't know which command threw the error for your logging and user input.