Someone asked how to convert from an integer to string in Visual Basic/VBA. The answer, Visual Basic will do this automatically. Observe the following code:
Sub test()
Dim i As Integer
Dim s As String
i = 5
s = i
MsgBox s, vbOKOnly, "Test"
End Sub
In the above code, I will automatically be converted to a String, no extra code is necessary. Technically, it could be re-written as:
Sub test()
Dim i As Integer
i = 5
MsgBox i, vbOKOnly, "Test"
End Sub
However, I feel that using the intrinsic functions of Val() and Str() are a little better since it clearly shows that you are converting from one type to another. Observe the below code:
Sub test()
Dim i As Integer
Dim s As String
i = 5
s = Str(i)
MsgBox s, vbOKOnly, "Test"
i = Val(s)
End Sub
Here, we can clearly tell by using the Str() function that we are converting from a number, and vice-versa with the Val() function. I feel that for clear understanding for future maintainers, this is a better approach. Interpreted languages such as VB and Perl that do automatic type conversion promote bad programming practices and I feel that type conversions such as this are a crutch for lazy programmers. I myself am guilty of this since I sometimes make exceptions when I am assigning a value to a textbox, however this is a habit I should break myself of. Programming isn’t just about writing code that works, it is also about writing code that can be maintained and understood by other developers.
Thank you!
ReplyDeleteconversion of string to an integer?????
ReplyDeletewarning: str inserts white space.... just to give you another problem to solve.
ReplyDeletewouldn't want you getting bored or anything.
str to int -> val()
ReplyDeletebut when i enter:
ReplyDeleteascii3=173
length=Len(ascii3)
i get length = 4
Use cstr()
ReplyDeleteor Trim(str(123))
how to convert the integer to text, for example 5 to "*****"..?
ReplyDeleteusing do while or do until or for next,,
tq very2 much..
Thanks. I was getting an error concantenating an integer to a string. I needed to explicitly cast the integer as a string for the concantenation to work, and this tip did the trick.
ReplyDeleteThank you. I've been searching for this for a while now.
ReplyDeletehow to remove that extra space generated by str()... i want to cnvert int to string in a path and that space is causing problem.. help me
ReplyDelete