RDC11011 — Variant number compared with a Variant String
Severity: Warning · Family: RDC (Rubberduck Core analyzers) ·
Raised by: VariantNumberStringComparisonAnalyzer
A comparison operator - =, <>, <, >, <=, >= - compares a Variant that holds a number with a Variant that holds a String. The number is always less
than the String, whatever the two values are.
This is how VBA compares them (MS-VBAL §5.6.9.5 Relational Operators): when both operands are Variant
values, a number is never compared with the text of a String. So, with a and b both declared As Variant:
a = 5andb = "4":a < bisTrue, although 5 is more than 4.a = 10andb = "9":a > bisFalse.a = 5andb = "5":a = bisFalse.
When either operand is declared with a type, the values are compared: with a declared As Long, a < b is False.
The code is legitimate, but it is almost never what is meant. A number typed into an InputBox, read from a cell or from a text file is a String, and a Variant
holding it compares as one: For i = 1 To n then counts up to a String that every number is less than, and If i <= n Then is always True. The result does not
depend on the values, which is why this is a warning.
How it is raised
| Situation | Example | Resolution |
|---|---|---|
A Variant holding a number is compared with a Variant holding a String. |
n = InputBox("How many?") then If i <= n Then, with n and i declared As Variant |
Convert the String to the number it stands for: n = CLng(InputBox("How many?")), or declare n As Long. |
| The two values are meant to be compared as text. | If code = reference Then, where code holds 5 and reference holds "5" |
Convert the number: If CStr(code) = reference Then. |
See also
ACCUEIL • HOME | ℹ️ BIENVENUE • WELCOME | 🧩 BÂTISSONS • BUILD | RD-VBAL | SDK | 🌐 rubberduckvba.ca