Datatypes in VbScript

VBScript DataTypes

Datatypes in VbScript
VBScript DataTypes used in UFT
Datatypes in VbScript

Data Types in VBScript:

VBScript has only one data type called a Variant. A Variant is a kind of super data type that can contain different kinds of information.So in nutshell the variant is a special data type that can store many different subtypes. Some other thought says that variant is merely a container for several other data types.

A variant data type changes automatically depending on what kind of data the variable is holding. This concept becomes important when we have VBScript code that needs to interact with COM components.(They may be written in VB,C++ or other COM enabled languages).

The downside of variant is that it takes up more spaces (memory) than many of the specified VB data types.

This post will help you to understand the following topics as well:

  1. what is variant data type in vbscript?
  2. is there any Datatype in Vbscript?
  3. data type in vbscript

VBScript is a loosely typed Language:

In Vbscript the coder need not have to declare the data type of a variable.However what kind of data the variable holds still matters to WSH. A loosely typed language does not provide a way to declare type of a variable. This is the reason we don’t see datatypes in VBScript.

In VbScript we have a super type fit for all, universal data type called Variant.Variant is the only data type in VBScript, It is same  data type returned by all functions in VBScript. It is kind of one fits for all.A subtype is a type within the type.

A variant is a type or called super type and remaining all other subtypes are the child type.
In other words a variant is a generic container in which all subtypes resides.

A variant can hold only one of the subtype at a time.The process of changing subtypes are called type conversion or implicit type coercion.By default the variant subtype will be integer.

The below discussion is very useful while designing automation framework.

Subtype of Variant:

There are two major subtypes of Variant data type:

  • Implicit
  • Explicit

Implicit:

When we change a subtype and a new value gets assigned to a variant variable, in that case an implicit change in the data subtype happens.In this case the VBScript engine checks the new data and determine automatically what subtype is should be. This automatic conversion is called Implicit type conversion.

Why Implicit option is not good always?

When we ask VBScript engine to define and store a data, it may select any of the relevant subtypes to store the data.Like a numeric data 5 can b stored in String,integer,long or byte.
On the other hand,if we want to make sure that the numeric data is stored inside predefined datatype like integer,we need to use CInt() conversion function.This will ensure that the number 5 is stored as Integer not any other data type.

Implicit type Conversion:

This is a technique where variant variable changes its subtype as per engine defined rules automatically.


Dim a
a=InputBox("Enter a Number that will be multiplied by 10")
Msgbox TypeName(a)
If IsNumeric(a) Then
Msgbox TypeName(a)
a=a*10
Msgbox TypeName(a)
Msgbox "Multiplied by 10 gives"&a
Else
Msgbox "Wrong Input"
End If

Here a is changed from String to int to long based on the content.We can test the type value by using TypeName() method.The first TypeName is String as WSH notices that the data is coming from InputDialogBox. The second TypeName is calculated based on the number we provide. The third TypeName is calculated when the resultant number is too long for integer.

Explicit:

The second way to change a subtype to a variant is explicit type conversion.In this process instead of automatic type identification ,the coders themselves takes specific measures to change the subtype. This type of conversions are done with different VBScript syntaxes and conversion functions.
We can also declare a variable implicitly by simply using its name in our script. That is not generally a good practice because we could misspell the variable name in one or more places, causing unexpected results when our script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables.

Option Explicit in VBScript:

The Option Explicit statement should be the first statement in our script.Forces explicit declaration of all variables in a script.As in VBScript,the variable declaration is optional ,that signifies that we can declare or we may not declare a variable before using it.Even though this feature makes the VBScript engine very fast but can cause issues if we do spelling mistake.(VBScript may not catch the spelling mistake a error instead it will create a new variable which may create a bug). To overcome this issue VBScript provides a powerful concept called Option Explicit. We need to put it in the first line of the script. It tells the VBScript engine that all variables used in the script are explicitly declared before they are used. It stop spelling mistake of a variable as a new variable.

 


Option Explicit ' Force explicit variable declaration.
Dim MyVar ' Declare variable.
MyInt = 10 ' Undeclared variable generates error.
MyVar = 10 ' Declared variable does not generate error.
 

VBScript Variant Subtypes:

Beyond the simple numeric or string classifications, a Variant can make further distinctions about the specific nature of numeric information. For example, we can have numeric information that represents a date or a time. When used with other date or time data, the result is always expressed as a date or a time. We can also have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers. These different categories of information that can be contained in a Variant are called subtypes. Most of the time, we can just put the kind of data we want in a Variant, and the Variant behaves in a way that is most appropriate for the data it contains.
The following table shows subtypes of data that a Variant can contain.

VBScript Subtype Description:

This list is very much useful while working with data types.

SubtypeDescriptionTest FunctionvarType()TypeName() return value
EmptyA variant is uninitialized. Value is 0 for numeric variables or a zero-length string (“”) for string variables.No Conversion function available.IsEmpty()-returns True/False based on the variable under test is initialized or not.0(vbEmpty)Empty
NullVariant intentionally contains no valid data..No Conversion function availableIsNull()-returns True/False based on the variable under test is having any data or not1(vbNull)Null
BooleanContains either True or False. Conversion function -CBool()No Test function11(vbBoolean)Boolean
ByteContains integer in the range 0 to 255.
Conversion function-CByte()
IsNumeric()-returns True/False based on the variable under test is numeric or not.17(vbByte)Byte
IntegerContains integer in the range -32,768 to 32,767.Conversion function-CInt()IsNumeric()-returns True/False based on the variable under test is numeric or not.3(vbInteger)Integer
Currency-922,337,203,685,477.5808 to 922,337,203,685,477.5807.Conversion function-CCur()IsNumeric()-returns True/False based on the variable under test is numeric or not.6(vbCurrency)Currency
LongContains integer in the range -2,147,483,648 to 2,147,483,647.Conversion function-CLng()IsNumeric()-returns True/False based on the variable under test is numeric or not.2(vbLong)Long
SingleContains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.Conversion function-CSng()IsNumeric()-returns True/False based on the variable under test is numeric or not.4(vbSingle)Single
DoubleContains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.Conversion function-CDbl()IsNumeric()-returns True/False based on the variable under test is numeric or not.5(vbDouble)Double
Date (Time)Contains a number that represents a date between January 1, 100 to December 31, 9999.Conversion function-CDate()IsDate()-returns True/False based on the variable under test is Date or not.7(vbDate)Date
StringContains a variable-length string that can be up to approximately 2 billion characters in length.Conversion function-CStr()None8(vbString)String
ObjectContains an object.
No Conversion function available
IsObject()9(vbObject)Object
ErrorContains an error number.
No Conversion function available
No Test Function10(vbError)Error
VariantSuper type for all
Conversion function-CVar()
No Test Function12(vbVariant)Variant
DecimalContains decimal data.
No Conversion function available
IsNumeric()-returns True/False based on the variable under test is numeric or not.14(vbDecimal)Decimal
ArrayContains multiple data
No Conversion function available
IsArray()-returns True/False based on the variable under test is array or not.8192(vbArray)Array

We can use conversion functions to convert data from one subtype to another. In addition, the VarType function returns information about how your data is stored within a Variant.

There are two more functions that also can be considered as Test functions:

  • IsFinite()-returns True/False based on the variable under test is finite or not.
  • IsNaN()-returns True/False based on the variable under test is NAN (Not a Number)or not.

How to check data type of a variant variable?

There are two inbuilt functions in VBScript that returns the datatype of a variant in two different flavors.
The functions to check datatype as follows:

  • VarType()
  • TypeName()

VarType Function:

This function returns a numeric representation of the underlying subtype of the variant.

TypeName Function:

This function returns a String representation of the underlying subtype of the variant.

Example:

Dim a
a="xyz"
msgbox VarType(a)   //also it can be coded like below:
If VarType(a)=VBString Then
msgbox "Hello"
End If
//also can be expressed as:
If VarType(a)=8 Then
msgbox "Hello"
End If

For Constants in VBScript Please refer here. However if we write values instead of the named constants,it will create issues in understanding later. The named constants improved readability and understandability of the expression.

Force Datatype change in Vbscript:

This is a very useful concept while designing the UFT script or VBScript or QTP script.


dim a
a=10
msgbox TypeName(a)//output as integer
a="10"
msgbox TypeName(a)//output as String
a=CLng(a)
msgbox TypeName(a)//output as long
//this is often referred as side effect of CLng() function.
 

Empty Datatype:

Empty is a subtype of variant.When we define a variable but not assign a value to int,it is Empty and its type is also empty.Empty is implicit as the WSH engine assigns it by default.

Dim a
Msgbox TypeName(a) 

we can not work with this Empty data type or Empty variable.We can however convert an Empty to other sub data type.If the conversion type is of the numeric type then the value is converted to zero(0) by default.If the conversion is of String type, it will create a empty zero sized or length based String.

How to check if a datatype is empty?

There is a function called IsEmpty() that returns a boolean value,depending on emptiness of the variable.

Null Datatype:

A variant can hold Null value once the coder has explicitly assigned a Null to a variable. Null datatype says there is no value or the value is  unknown. Null is explicit as either coder has to to do it or some external trigger like Database,Some query or some functions can produce it.

Empty Vs Null- comparison

  • Empty data type indicates that the variable is declared but not assigned with any value whereas Null indicates that the variable does not hold any valid data. Or the Null also signifies that the variable is assigned with a NULL subtype.
  • Empty is implicit and Null is explicit.

How to assign Null value to a variable in VBScript?

Dim a;
//now a is empty not Null
a=Null
//Null is assigned to a 

We can not compare a variable having Null value using = operator,We need to use IsNull() function to test if a variable is Null.


//illegal
If a=Null Then
Msgbox "a is Null"
End if
//legal
If IsNull(a) Then
Msgbox "a is Null"
End if
 

Invalid Use of Null Issue in VBScript or UFT or QTP

We need to be careful about working with a variable having Null value.In an expression,if one variable holds Null,the expression can not be evaluated.Instead VBScript engine will throw an error message as “Invalid use of Null”


Dim a,b,c
a=Null
b=5
c=a+b
Msgbox c
Msgbox TypeName(c) //output Null
 

This is a very popular error code when UFT/QTP tries to read from Database and tries to do some operation.The better way to work with it is to check using IsNull() and then assign some value based on TypeName() function.

Trim() function will also return Null if operated on a Null variant.

Object Datatype:

Object is a subtype of variant that can hold reference to an Object.An Object contains properties and methods. The object data type is generic and can hold a reference to any kind of object. An object is a very convenient way to represent the encompassed data and methods.

Object references store in a variable of the object data type are known as late bound. It means that object interface can not be resolve until runtime. Variables and routine parameters can be declared as a specific object type. But they are known as early bound. It means that the interface of the object was known at compile time.

A late bound variant object variable can be passed to a VBScript procedure that uses an early bound parameter.

How to Work with Object?


Dim objFSO
Dim bolFilePresent
Set objFSO=WSScript.CreateObject("Scripting.FileSystemObject")
bolFilePresent=objFSO.FileExists("Path of the file")
msgbox bolFilePresent
set objFSO=Nothing
 

Object variables need to be destroyed when we are done with the use of those variables. Nothing is same as Null. It instructs the VBScript engine that the usage of the variable is over and it is ready to be garbage collected.

The VBScript engine destroys the object and reclaim it’s memory for other usage.This approach is safe during framework development where we need lots of objects to be created. It also helps us to reduce “fatal memory error” issue.

Error:

This is another subtype of the variant data type.It can contain result of the function or error number and description. VBscript does not really support the Error subtype and the chance of getting such variable is very minimal.

Decimal

VBscript does not really support the Decimal subtype and the chance of getting such variable is very minimal.

Data Coercion

Vbscript or UFT only support variant data type(internally it has different sub types). The process of variant to internal sub data type mapping is automatic.

However VBScript provides us ways where a coder can determine the sub types.This helps coders and VBScript to work with proper subtypes and wrong mapping side effects.

There are two types of Data coercion:

  1. Implicit Coercion
  2. Explicit Coercion

Implicit Coercion

In this process, VBScript engine automatically transform variant to underlying sub types. This automatic transfer of sub types sometimes are very good and user friendly and sometimes it may fail.

When VBScript engine sees the data type and the corresponding operations, it just transfers the data type for being safer during operation. However, implicit type conversion does not happen on random basis. It just happen when we change the data of the current variable.

TypeName() is the function that can return :

  1. Byte
  2. Integer
  3. Long
  4. Date
  5. String
  6. Boolean
  7. Empty
  8. Null
  9. Object
  10. Unknown
  11. Error

Explicit Coercion

In this process coders can transform a variant to one of the desired sub types.

The below are the conversion functions to explicitly data type change.

  1. Asc()- Returns the ANSI character of the first letter of the String.
  2. CBool()-Returns the Boolean value of the variable after a conversion.
  3. CByte()- Returns the Byte information of a variable after conversion.
  4. CCur()- returns the Currency information of a variable after conversion.
  5. CDate()-returns the Date information of a variable after conversion.
  6. CDbl()-returns the Double information of a variable after conversion.
  7. Chr()-returns the ANSI character information of a variable after conversion.
  8. CInt()-returns the Integer value information of a variable after conversion.
  9. Clng()- returns the Long value information of a variable after conversion.
  10. CSng()-returns the Single value information of a variable after conversion.
  11. CStr()-returns the String value information of a variable after conversion.
  12. Hex()-returns the Hex value information of a variable after conversion.
  13. Oct()-returns the octal information of a variable after conversion.

if VbScript is not able to convert a variable to its approved list(like conversion of an alphanumeric character to numeric one), it throws an error stating that “type mismatch”.

When we do not have control of the incoming data, it is better to use the default variant. Like the below scenarios:

  • take input from users
  • reading data from any database
  • reading files.

Share and Enjoy !

18 thoughts on “VBScript DataTypes”

  1. Good post however , I was wondering if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit more. Appreciate it!

  2. Way cool! Some extremely valid points! I appreciate you penning this write-up along with the other parts of the site is extremely good.

  3. It’s really a great and useful component of information. I’m glad which you shared this helpful information along with us. Please stay us up to date similar to this. Thanks for sharing.

  4. What i don’t realize is actually how you’re not actually considerably more well-appreciated than you could be today. You are so intelligent. You realize thus significantly pertaining to this matter, produced me for my part consider it from countless varied angles. Its like men and women aren’t involved unless it’s something to accomplish with Lady gaga! Your own personal stuffs excellent. On a regular basis handle it!

  5. When some one searches for his required thing, so he/she wishes to get available that in more detail, thus that thing is maintained right here.

  6. I was curious if you ever considered changing the layout of your own website? Its perfectly written; I adore what youve got to say. But you could possibly could a bit more in the form of content so people could get in touch with it better. Youve got so much of text for just having one or 2 images. You may could space it better?

  7. Have you ever thought about adding a little more than only your articles? I am talking about, whatever you say is valuable and everything. Nevertheless think of if you added some great visuals or video clips to present your posts more, “pop”! Your site content is great however with pics and clips, this website could undeniably be among the best possible in their field. Amazing blog!

  8. Terrific article! This is certainly the level of info that are supposed to be shared over the net. Disgrace on Google for now not positioning this post higher! Occur over and seek advice from my website . Thanks =)

  9. Way cool! Some very valid points! I appreciate you penning this article plus the rest of the website is also really good.

  10. Do you have a spam issue on this blog; I also am a blogger,
    and I was wanting to know your situation; many of us
    have created some nice procedures and we are looking to trade strategies with other
    folks, why not shoot me an email if interested.

  11. Ahaa, its fastidious conversation on the topic of this paragraph
    around this place at this website, We have read all that, so now me also commenting here.

  12. Superb blog! Have you got any recommendations for aspiring writers?
    I’m hoping to start my own site soon but I’m a little bit lost on everything.
    Can you advise beginning with a free platform like WordPress or go for a paid
    option? There are so many options out there
    that I’m totally confused .. Any suggestions? Kudos!

  13. It’s genuinely very difficult in this active life to listen news on TV, therefore I only
    use world wide web for that reason, and take the most up-to-date information.

  14. When I initially commented I appear to have clicked on the -Notify me when new comments are added- checkbox
    and from now on whenever a comment is added I recieve 4 emails with
    the exact same comment. Is there an easy method you can remove me from that service?
    Kudos!

  15. Simply want to say your article is as surprising.

    The clearness on your put up is just excellent and that i can suppose you are a professional in this subject.
    Fine together with your permission let me to snatch your RSS feed to stay
    up to date with imminent post. Thank you one million and please continue the gratifying work.

  16. I do not know if it’s just me or if perhaps everybody else experiencing problems
    with your website. It appears like some of
    the text in your posts are running off the screen. Can someone else please comment and
    let me know if this is happening to them as well?

    This might be a issue with my browser because I’ve had this happen before.

  17. I really do trust every one of the concepts you’ve offered
    to the post. They’re really convincing and will certainly work.

    Still, the posts are very brief for starters. May you please extend them somewhat from subsequent time?
    Thanks a lot for your post.

Leave a Comment

Your email address will not be published. Required fields are marked *