VbScript is loosely typed language.
You can use a variant with out define like this:
MyVar = 50 or MyVar = "UserName"
The only one data type in vbscript is Variant.
There are subtypes such as Integer, Long, Single, Double, Currency, Date, String, Boolean, Decimal, Byte, and so on.
You can use VarType() and TypeName() to get data type.
Dim MyVar
MyVar = #04/06/2013 09:45 PM#
MsgBox TypeName(MyVar)
The following 3 block will get same result:
Dim MyVar
MyVar = 10
MsgBox TypeName(MyVar)
Dim MyVar
MyVar = CInt("10")
MsgBox TypeName(MyVar)
Dim MyVar
MyVar = "10"
MyVar = CInt(MyVar)
MsgBox TypeName(MyVar)
Theoretically, the first block is faster.
Two implicit type coercion:
Dim myInt
myInt = 100
MsgBox TypeName(myInt)
myInt = myInt + 1000000
msgBox TypeName(myInt)
myInt = myInt + 10000000000
msgBox TypeName(myInt)
Dim myInt
myInt = InputBox("Please input your age:")
MsgBox TypeName(myInt)
If IsNumeric(myInt) Then
myInt = myInt + 20
MsgBox TypeName(myInt)
MsgBox "In 20 years, you will be " & myInt & "years old. " & TypeName(myInt)
Else
MsgBox "Please input a valid number."
End If
In order to make our code more clear, we should try to avoid implicit type coercion.
We can add prefix for our variant such as:
var Variant
str String
int Integer
lng Long
byt Byte
sng Single
dbl Double
cur Currency
obj Object
bool Boolean
We offten can't ascertain the data type of a variant, so we need to know the exact data type before our convert,
because the unsuitable data type convert will result in runtime error.
We can use "Is" function to avoid type mismatch, such as:
IsNumeric()
IsDate()
IsArray()
IsObject()
IsEmpty()
IsNull()
If IsNumeric(20) Then
MsgBox "pass"
End If
If Not IsNumeric("abc") Then
MsgBox "not a data"
Else
MsgBox "a data"
End If
Only use "&" to connect strings. Only use "+" to add numbers. Don't use "+" to connect strings.
This is a bad demo:
Dim strFirst
Dim intSecond
strFirst = CStr(50)
intSecond = CInt(100)
MsgBox strFirst + intSecond
"Empty" means havn't done initialization
Dim MyVar
MsgBox MyVar
MsgBox CInt(MyVar)
MsgBox CStr(MyVar)
Dim MyVar
MyVar = 20
MyVar = Empty
"Null" means this is not an exact value.
The following demo tell us we get a not exact value from an exact value add with a not exact value.
Dim VarTest
Dim lngTest
VarTest = Null
lngTest = 2+VarTest
MsgBox TypeName(lngTest)
When we get data from data base, if we can't make sure the data is null or not, we can use following code to avoid error cause by null.
strUserName = "" & rsUser.Fields("Name").Value
strNmae = Trim("" & rsUser.Fields("Name").Value)
strNmae = UCase("" & rsUser.Fields("Name").Value)
strNmae = Left("" & rsUser.Fields("Name").Value, 5)