So for some reason you have the need to use vbscript (maybe a .vbs file, Excel script, etc) but like many others before you, you have run into a limitation of vbscript. I’m not going to discuss the reasons why / why not to use vbscript, I am already assuming you have a good reason. Onto the example. In this case, we are “fixing” the limitation of vbscript to not handle larger numbers well. We are going to extend our vbscript by creating a .dll library in Visual Studio that allows us to pass and return data in the format we need, in the example case, to round a large decimal number.
- So let’s first fire up Visual Studio and create a “Class Library”. In my case I called it: sampleMathLibrary and used vb.net.
- In the AssemblyInfo.vb, set this to be true: <Assembly: ComVisible(True)>
- Toss in some functions:
Imports System Public Class mathLibrary Public Function roundNumber(number As String) As String Dim roundedNumber As String = "" Dim largeNumber As Decimal = 0 If IsNumeric(number) Then largeNumber = Convert.ToDecimal(number) roundedNumber = FormatNumber(largeNumber, 0, TriState.UseDefault, TriState.UseDefault, TriState.False) End If Return roundedNumber End Function End Class
- You need to register your .dll for use in vbscript, so using the regasm tool, run this:
regasm C:\PathToYourDll\samplemathlibrary.dll /codebase
- Now create / update your vbscript to utilize the “CreateObject” and your new functions:
dim mathLib set mathLib = CreateObject("sampleMathLibrary.mathLibrary") Dim num 'some huge number num = 4895390000000005 'just to see how vbs would handle - WRONG msgbox(FormatNumber(num,0,-2,-2,False)) 'now fix for our function num = "4895390000000005" 'so good msgbox mathLib.roundNumber(num)
That’s all you need. Sure, it’s not pretty, but if you have legacy code that needs to be extended, the sky is the limit!
Thanks for the post. Can you point to any references that expand on this topic? Thanks!
LikeLike