VBA If Test Gives Wrong Result

ghborrmann

New Member
Joined
Mar 5, 2018
Messages
1
I have just finished a considerable effort in tracking down a bug in one of my Excel macros. While I know how to fix this bit of code, I am unsure of how to deal with the generic problem this raises. The bug occurred in the following VBA statement:
Code:
If qty < oldqty Then
    Some code
End If
The above test failed, with qty and oldqty equal to 167 and 280, respectively. After much head-scratching, I finally figured out that, although both variables are Variants, they have different vartypes: qty is a string, and oldqty is an integer. If I convert qty to an integer, the code works as expected.

I have never worried much about variable types in VBA. Unlike strongly typed languages, I always assumed that VBA would convert types as needed. In fact, this is almost always what happens. Now, I am wondering what other bugs may exist in my other macros, and what I should do about this. Should I avoid using Variants altogether? I would appreciate any comments or advice.
 

Excel Facts

Control Word Wrap
Press Alt+Enter to move to a new row in a cell. Lets you control where the words wrap.
Absent a specific need for a Variant, I would always use strongly-typed variables. Faster, smaller memory footprint, and not subject to errors like that.
 
Upvote 0

Forum statistics

Threads
1,223,243
Messages
6,170,964
Members
452,371
Latest member
Frana

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top