RDC11013 — Variant compared with a String as text
Severity: Warning · Family: RDC (Rubberduck Core analyzers) ·
Raised by: VariantComparedWithStringAsTextAnalyzer
A comparison operator - =, <>, <, >, <=, >= - compares a Variant that holds a number, a Date or a Boolean with a String that is not a
Variant: a variable declared As String, or a string literal. VBA compares the two as text: the Variant's value is turned into its text first.
So, with v declared As Variant and s declared As String:
v = 10ands = "9":v > sisFalse, because the text"10"comes before"9".v = 1.5ands = "1.5":v = sisTrue.v = 0ands = ".":v = sisFalse, and no error is raised.
This is what Microsoft Office VBA does, and what Microsoft Learn documents ("One expression is a String and the other is any Variant except a Null: perform a
string comparison"). The language specification says otherwise: MS-VBAL §5.6.9.5 makes the
comparison a numeric one, which raises run-time error 13 (Type mismatch) when the String is not a number. RD-VBA runs the code as VBA does, and this warning
stands in for that type mismatch: the code depends on a behaviour the specification does not give it.
It is also rarely what is meant. A number compared as text is ordered by its digits, not by its value.
How it is raised
| Situation | Example | Resolution |
|---|---|---|
A Variant holding a number is compared with a String that holds a number. |
If amount > limitText Then, with amount a Variant holding 10 and limitText holding "9" |
Convert the String: If amount > CDbl(limitText) Then. |
| The two values are meant to be compared as text. | If code = reference Then, with code holding 5 and reference declared As String |
Say so: If CStr(code) = reference Then. |
See also
- RD-VBAL §2.6.4 Rubberduck Core Diagnostics
- RD-VBAL §5.6.9.5 Relational Operators
RDC11011: twoVariantvalues, a number and aString
ACCUEIL • HOME | ℹ️ BIENVENUE • WELCOME | 🧩 BÂTISSONS • BUILD | RD-VBAL | SDK | 🌐 rubberduckvba.ca