Connection Handling

It is not recommended that you place SapGuiOpenConnection calls in main transactions, otherwise each user opens a new connection with each transaction iteration. Because the SAPGUI scripting API performs connection closes asynchronously, this leads to the problem that your load test agents will open too many connections to the SAP server simultaneously. Errors will then result if you exceed the maximum connection limit.

Unless you are interested in load testing the establishment of new connections, it is recommended that you move logon procedures to INIT transactions. Furthermore, main transactions should always end at the same location where they begin, which is likely to be the screen after a successful logon.

Likewise, logout sequences should be moved out of main transactions and into end transactions.

A fully customized script should resemble the following:
dcluser
  user
    VUser
  transactions
    TInit           : begin;
    TMain           : 1;
    TEnd            : end;
var
  gsConnID : string;

dcltrans
  transaction TInit
  begin
    // Connecting to SAP
    gsConnID := SapGuiOpenConnection("CONNECTSTRING");
    SapGuiSetActiveConnection(gsConnID);
    SapGuiSetActiveSession("ses[0]");
    SapGuiSetActiveWindow("wnd[0]");
    // Logon to SAP System
    // Before running a test you have to customize the password
    parameter!
    SapGuiIgnoreError(SAPENGINE_STATUSBAR_CHANGED, SEVERITY_SUCCESS);
    SapGuiLogon("username", "password", "000", "", "SapGuiLogon");
  end TInit;

  transaction TMain
var
  begin
    SapGuiSetActiveWindow("wnd[0]", "SAP Easy Access", SAP GUI_MATCH_
    ExactNoCase);
...
...
...
    // The VUser should now be again back on the window after a
    successful logon
  end TMain;

  transaction TEnd;
  begin
    SapGuiPressButton("tbar[0]/btn[15]", "SapGuiPressButton\\btn[15]");
    // Log Off
    SapGuiSetActiveWindow("wnd[1]", "Log Off", SAP GUI_MATCH_
    ExactNoCase);
    // Yes
    SapGuiPressButton("usr/btnSPOP-OPTION1", "SapGuiPressButton\\Yes");
  end TEnd;