Why is Excel VBA letting me multiply strings?

GBarnes

New Member
Joined
Sep 30, 2011
Messages
1
I WANT Excel to tell me that I can't multiply a string. What am I missing?

Code:
Option Explicit

Sub why()
Dim myVariable As String
Debug.Print VarType(myVariable), TypeName(myVariable), myVariable
myVariable = 42 'Not "42"
myVariable = myVariable * 3 '126   Why?
Debug.Print VarType(myVariable), TypeName(myVariable), myVariable
End Sub
 
Last edited:

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.
Implicit Coercion

Many programming languages support the conversion of a value into another of a different data type. This kind of type conversions can be implicitly or explicitly made. Implicit conversion, which is also called coercion, is automatically done. Explicit conversion, which is also called casting, is performed by code instructions. This code treats a variable of one data type as if it belongs to a different data type. The languages that support implicit conversion define the rules that will be automatically applied when primitive compatible values are involved.
 
Upvote 0
there are several dissertations on this by people like John Walkenbach and Chip Pearson and others where they discuss how a number is a number by any other name and VBA will treat a number as a number, with exceptions. But they are generally referring to math functions when they talk about the numbers being numbers no matter what else you call them. The string data type allows us to use numbers for such things as sheet names or to use leading zeros, etc. But they are still numbers.
 
Upvote 0

Forum statistics

Threads
1,223,227
Messages
6,170,848
Members
452,361
Latest member
d3ad3y3

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