IF, Else, End IF, Exists in QTP/UFT with Example

โšก Smart Summary

IF Else End If statements let UFT and QTP scripts branch based on runtime conditions, while the Exist property checks whether an object appears on screen before the branch executes, covering ElseIf, nested If and Select Case as well.

  • ๐Ÿ”€ Basic syntax: If…Then pairs with an optional Else block and closes with End If, running exactly one branch per evaluation.
  • ๐Ÿงฎ Multiple conditions: ElseIf checks conditions top to bottom and stops at the first True match, replacing long chains of separate If blocks.
  • ๐Ÿช† Nested logic: Placing an If inside another Then or Else section handles dependent checks; keep nesting to two or three levels for readability.
  • ๐ŸŽฏ Select Case: Compares one variable against several fixed values and reads more clearly than a long ElseIf chain.
  • ๐Ÿ” Exist property: Returns True or False for whether an object is on screen, the standard condition for If Else branching.
  • ๐Ÿงช Applied example: Combine If Else with Exist to route a script into a negative or positive Flight Reservation login path automatically.
  • ๐Ÿค– AI assistance: AI tools can draft If Else and Select Case blocks and flag missing End If statements during debugging.

What is IF Else Statement in UFT/QTP?

The IF Else statement is the most common conditional control structure in VBScript, the scripting language used to write UFT/QTP automation scripts. It lets a script make a decision at runtime: when a condition evaluates to True, one block of statements runs, and when it evaluates to False, a different block runs instead. Testers rely on this construct constantly, for example to branch a script when a login succeeds versus when it fails, or when an object may or may not appear on screen. For the complete list of conditional statements and comparison operators VBScript supports, see the VBScript Conditional Statement guide.

The basic form pairs If…Then with an optional Else block and always closes with End If. UFT/QTP evaluates the condition once. If it is True, only the statements between Then and Else run; if it is False, only the statements between Else and End If run, and only one branch ever executes. The syntax below checks a numeric value and displays a different message box for each outcome.

Dim iValue
iValue = 25
If iValue > 18 Then
    MsgBox "Eligible"
Else
    MsgBox "Not Eligible"
End If

In UFT/QTP, the condition almost always compares an object property, a checkpoint result, or the return value of the Exist property rather than a plain number, since most scripts validate an application under test instead of doing arithmetic. Every example further down this page builds on the same If…Then…Else…End If pattern shown above; only the condition changes. Whichever condition you use, always test both the True and False paths at least once before moving the script into a regression suite.

IF…Then…ElseIf…Else Statement in UFT/QTP

A plain If Else only ever chooses between two outcomes. When a script needs to test three or more mutually exclusive conditions, VBScript adds ElseIf to the same block. UFT/QTP checks each condition from top to bottom and runs the first block whose condition is True; every other block, including the trailing Else, is skipped. This keeps a script far more readable than nesting several unrelated If blocks inside one another.

  • Conditions are evaluated top to bottom, and evaluation stops at the first condition that is True.
  • Each ElseIf keyword needs its own Then and its own condition.
  • The trailing Else is optional and only runs when none of the conditions above it match.
  • Only one End If closes the entire block, no matter how many ElseIf branches it contains.
Dim iMarks
iMarks = 75
If iMarks >= 90 Then
    MsgBox "Grade A"
ElseIf iMarks >= 75 Then
    MsgBox "Grade B"
ElseIf iMarks >= 50 Then
    MsgBox "Grade C"
Else
    MsgBox "Fail"
End If

The script above prints a different grade for each score range and stops checking further conditions the moment one branch evaluates to True, which keeps large decision trees efficient even inside a long automation run.

The same pattern applies directly to UI checks: a script might read a status field’s value and use ElseIf to route into pass, warning or fail handling depending on the text it finds, instead of three separate If blocks that each re-evaluate the field independently.

Nested If Statement in UFT/QTP

A nested If places one complete If…End If block inside the Then or Else section of another If block. UFT/QTP resolves the outer condition first and only evaluates the inner If when that outer branch is entered. This pattern suits checks that depend on each other, such as confirming a user is old enough to vote and then branching again on gender, rather than combining every condition into one long expression with And and Or. Keep nesting shallow, generally no more than two or three levels, because each extra layer makes a script harder to trace and debug. In UFT/QTP terms, a nested If commonly checks the operating system first and then branches again on the browser or application state, so the inner block only runs once the outer context is confirmed.

๐Ÿ’ก Tip: Indent each nested block by one extra level and give every End If its own line. Consistent indentation is the fastest way to catch a missing End If before the script fails at runtime.

Dim iAge, sGender
iAge = 20
sGender = "Male"
If iAge >= 18 Then
    If sGender = "Male" Then
        MsgBox "Eligible male voter"
    Else
        MsgBox "Eligible female voter"
    End If
Else
    MsgBox "Not eligible to vote"
End If

Select Case Statement in UFT/QTP

Select Case is an alternative to a long ElseIf chain when every branch tests the same single variable against a different fixed value. UFT/QTP evaluates the expression on the Select Case line once, then compares it against each Case value in order and runs the first block that matches. An optional Case Else catches any value that none of the listed cases cover, similar to the trailing Else in an If block. Because the comparison variable is written only once, a long Select Case block is also easier to update later than an equivalent chain of ElseIf statements that repeats the same variable name in every branch.

Case values are compared using equality and are case sensitive, so “Chrome” and “chrome” count as different matches unless the value is normalised first, for example with the LCase function. See the VBScript Variable Declaration guide for how Dim and data types affect these comparisons.

Dim sBrowserName
sBrowserName = "Chrome"
Select Case sBrowserName
    Case "Chrome"
        MsgBox "Launching Chrome"
    Case "Firefox"
        MsgBox "Launching Firefox"
    Case "Edge"
        MsgBox "Launching Edge"
    Case Else
        MsgBox "Browser not supported"
End Select
STATEMENT BEST FOR NUMBER OF CONDITIONS READABILITY AT SCALE
If…Else Two outcomes 1 condition High
If…ElseIf…Else Several unrelated conditions 3 or more conditions Drops as branches grow
Select Case Many fixed values of one variable Any number Stays high

Case can also match a range using the Is keyword, for example Case Is > 90 inside a Select Case block, which lets a single case cover every value above a threshold instead of listing each one individually.

Choose Select Case whenever a script tests one variable against many possible values; keep If…ElseIf for conditions that compare different variables or use ranges and logical operators.

How to Use IF Else with the Exist Property in UFT

Click here if the video is not accessible

The Exist property returns True or False depending on whether an object is currently present in the application under test, which makes it the natural condition to pair with If Else. The example below revisits the classic Login Functionality scenario for the Flight Reservation application from the Testing series, where a script must branch into a negative-scenario path when an error dialog appears, or a positive-scenario path when it does not. This mirrors the exact Test Scenario covered in the video above.

  1. Record two separate scripts: one that logs in with a valid Agent Name and Password combination, and one that logs in with an invalid combination.
  2. Insert an If Else step immediately after the login step so both recordings can run inside a single combined script.
  3. Set the condition to check whether the Error Information window exists, using the Exist property instead of a Click step.
  4. Move the negative-scenario steps, such as closing the error window and the login dialog, inside the If block.
  5. Move the positive-scenario steps, such as closing the Flight Reservation window, inside the Else block.
  6. Save the combined script and run it against both a valid and an invalid credential set to confirm each path executes correctly.
Dim bLoginFailed
bLoginFailed = Browser("Flight Reservation").Page("Flight Reservation").WinObject("Error").Exist(5)

If bLoginFailed Then
    'Negative scenario - invalid login
    Browser("Flight Reservation").Page("Flight Reservation").WinObject("Error").Close
    Dialog("Login").Close
Else
    'Positive scenario - valid login
    Window("Flight Reservation").Close
End If

Apart from If and Else, VBScript also supports While…Wend and For…Next loops for repetition, plus the ElseIf and Select Case statements covered above for extra branches. Combining these constructs with the Exist property is what lets a single UFT/QTP script handle both a positive and a negative test scenario without manual intervention.

โš  Note: Passing a longer value to Exist, such as Exist(10), makes UFT wait longer for an object before returning False, which is useful for slow-loading dialogs but can slow the whole suite if used on every step. Reserve long waits for genuinely slow objects. A short, well-chosen timeout keeps the combined positive and negative scenario script both reliable and fast to execute in continuous test runs.

FAQs

ElseIf evaluates conditions in sequence and stops at the first match, making it faster and clearer than several independent If blocks. Use separate If statements only when conditions are unrelated and every one of them must be checked.

Exist uses the UFT default synchronization timeout, typically a few seconds, unless a custom value such as Exist(10) is passed inside the parentheses to wait longer for a slow-loading object.

Yes. AI assistants can draft If, ElseIf, and Select Case blocks from a plain-language description of the test logic, though testers should still verify object names, properties, and timeout values before running the script.

AI tools can scan a script, flag mismatched End If statements and unreachable Else blocks, and suggest fixes, which speeds up debugging compared with a manual line-by-line review of long scripts.

Yes. Use the Is keyword inside a Case line, for example Case Is > 90, to match every value above a threshold instead of listing each one individually.

Summarize this post with: