Type Casting in Excel VBA

Recently, I was on an assignment. I was creating a MS-Excel based dashboard for a project. One of the requirement was to display complete status and update of the project. For this user was supposed to enter Project-ID. It was defined as long in the data base. For this, I created a Form and asked user to enter Project-ID. As soon as, user presses “Ok” after entering a valid Project ID, the relevant data related to the project gets listed. Internally, I searched for Input Project-ID. Once the match is found, corresponding data was displayed. I wrote a simple piece of code to perform this operation. But it failed in execution. The code was unable to find a match, though input Project-ID was present in Database. After a round of debugging, I found it was a result of type casting issue.

I made appropriate changes in my code ………….. Bingo!!! .. it worked.

Excel VBA supports type casting. It is very simple and easy, too.

For Example, to covert a Integer Type Temp  into String Temp_Str, we need to write Temp_Str = cstr(Temp) in VBA.

At another place, it was required to read and print a field which was defined as Date type. While priting, the date was getting converted into some random format.

To overcome this, I typecasted the read value to date type using cdate(Read_Date).

Bingo!! It worked again.

To get access to entire list of type-cast function, do following
1.       Go to object browser
 

2. Select "Conversion" 




3.Entire list of type cast function appear in the right window
 

Happy VBA….ing