Creating a .dll library for use in vbscript (.vbs) using Visual Studio

dllSo 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.

  1. So let’s first fire up Visual Studio and create a “Class Library”. In my case I called it: sampleMathLibrary and used vb.net.
  2. In the AssemblyInfo.vb, set this to be true: <Assembly: ComVisible(True)>
  3. 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
  4. You need to register your .dll for use in vbscript, so using the regasm tool, run this:
    regasm C:\PathToYourDll\samplemathlibrary.dll  /codebase
  5. 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!

Creating a .dll library for use in vbscript (.vbs) using Visual Studio

One thought on “Creating a .dll library for use in vbscript (.vbs) using Visual Studio

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s