Click here to Skip to main content
Click here to Skip to main content

How to call a .NET DLL from a VBScript

By , 12 Oct 2010
 

You might be wondering how you can call a .NET DLL from a VB Script. Well, look no further, as I will explain how to achieve this in a step by step manner.

You might be wondering why you want to do this?

Why not just do everything in .NET or VBScript?

Well there might be some instances where this will be useful, like modifying a start-up script for GPO which is already in VBScript, but you want to extend it safely (compiled codes) or just reuse available DLLs that are out there in your organization saving you time to redevelop the same thing again. There are a lot of reasons that you want to do this but this is why I am doing it, unless someone else suggests a better way of doing it. Anyways I am writing this so that if anyone needs this reference, it's just here.

Ok let's start with what you need. Definitely you need to develop or use an existing DLL. For this example, we will develop it from scratch, you also need the VBScript that you want to edit or create and that’s it.

Step 1: Your DLL. Fire up Visual Studio you can develop either in C#, VB or any language you want, this sample will be C#. You need to create a Class Library Project.

using System;
using System.Runtime.InteropServices;
namespace MyDLL
{
 [ComVisible(true)]
 public class Operations
 {
 [ComVisible(true)]
 public string getValue1(string sParameter)
 {
 switch (sParameter)
 {
 case "a":
 return "A was chosen";

 case "b":
 return "B was chosen";

 case "c":
 return "C was chosen";

 default:
 return "Other";
 }
 }
 public string getValue2()
 {
 return "From VBS String Function";
 }
 }
}

In the code above, apply the ComVisibleAttribute Class controls accessibility of an individual managed type or member, or of all types within an assembly, to COM. You can apply this attribute to classes, structures, interfaces, delegates, enumerations, fields, methods, assemblies or properties. By default, it is set to true but in case you want to hide the individual type, you can just set it to false (I just showed it for reference purposes, as you notice the getValue2 does not have that attribute, but still it is visible).

Build the project.

Now after creating this Class Library Project, you have to configure it so that when you compile it will register on the systems assembly. There are two ways of doing that; one is to a command prompt. If you have .NET Framework 2.0 installed, regasm would be in the following path at:

C:\windows\microsoft.net\Framework\v2.0.50727\regasm.exe

And use the following for registering and unregistering an assembly:

Register assembly manually

The one on top registers it and the one at the bottom unregisters it. Now what does that the /codebase option stand for? You need to use the /codebase switch when you don’t have your assembly in GAC because that will add an absolute path for your assembly in registry so that COM client can find it.

Another option is Directly to Visual Studio, this is the easy way and it’s as easy as ticking a check box in the project properties.

Register assembly

Now you have your DLL ready.

Step 2: Create your VBScript and here is my sample:

dim myObj
Dim myClass
Set myObj = CreateObject("MyDLL.Operations")
MsgBox myObj.getValue1("a")
MsgBox myObj.getValue2()

Now run your VBScript and that’s it.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Raymund Macaalay
Technical Lead
New Zealand New Zealand
Member
http://nz.linkedin.com/in/macaalay
http://anyrest.wordpress.com/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionref. How to call a .NET DLL from a VBScriptmemberMember 1001963830 Apr '13 - 0:19 
Hi,
 
Thanks for the article it's excellent.
 
i'm wondering if its possible someone can post a example on vb.net, i tried to change the C# example to vb.net, but i think that i'm doing something wrong because i get an error.
 
Thanks,
QuestionHow to call a VBScript's function from a .NET DLL?memberMember 97380557 Jan '13 - 21:58 
subject
QuestionHow to call a .NET DLL from a VBScriptmemberMember 25560031 Oct '12 - 2:52 
I have followed the same steps whatever you mentioned on the article, it works fine.
If i copied the same class libraries & script to another system and try to execute, its throwing out this error "ActiveX component can't create object"
In my .net class library i have the set the the platform target as "Any CPU".
Can you kindly tell me what i need to make it work in all systems???
 
Thanks
Divakar
AnswerRe: How to call a .NET DLL from a VBScriptmemberTL1000S4 Oct '12 - 3:28 
Are you sure you have followed the steps? Smile | :)
You have to use regasme.exe when copying your dll to another system.
Questionactivex component can't create objectmemberMember 928428820 Jul '12 - 9:25 
i've tried this example but the vbscript fails with an error that activex component can't create object. i also tried following the modified example in the comments. used regasm. any thoughts on what i'm doing wrong. used vs2010 for creating example. running on a windows 7 64bit box.
 
glenn
GeneralGood ArticlememberIrwan Hassan19 Oct '10 - 19:45 
Hi, it's a good article. I was looking for similar solution. I use HTA to develop small tools and wish to use the dot net. I also develop some dot net classes for some big software projects. It is nice to know that it is possible to reference a dot net class from VBS.
 
I guess it requires, dot net must be install on the client before we can use this application. If it is not required, please let me know as well. It will be another good news.
 
Thanks.
GeneralRe: Good ArticlememberRaymund Macaalay19 Oct '10 - 22:53 
Thanks for reading my article.
Unfortunately you need the .Net version you used when you developed the .dll so it can run, you also need it to register the assembly (regasm). Also based on experience if you are deploying it in 64 bit servers you need to register the assembly twice in 32 bit and 64 bit specially when your .dll is accessed by an application you dont know whether its compiled for 32 or 64 bit.
GeneralNice OnememberAnurag Gandhi18 Oct '10 - 20:51 
Very Useful for me.
Have my 5.
Thanks. Smile | :)
Anurag Gandhi.
http://www.gandhisoft.com
Life is a computer program and every one is the programmer of his own life.
My latest article: Group GridView Data

GeneralImproovements for your codememberReinhard Ostermeier13 Oct '10 - 5:11 
Even that your code is working, there are some attributes you should add to your objetcs/methods for good COM Interop.
 
Your code would look like this then:
using System;
using System.Runtime.InteropServices;
namespace MyDLL
{
   [ComVisible(true)]
   [Guid("282A7142-F792-4CC8-AAF9-4558128EAE75")]
   public class Operations
   {
      [ComVisible(true)]
      [DispId(0)]
      public string getValue1(string sParameter)
      {
         switch (sParameter)
         {
            case "a":
               return "A was chosen";
 
            case "b":
               return "B was chosen";
 
            case "c":
               return "C was chosen";
 
            default:
               return "Other";
         }
      }
      [DispId(1)]
      public string getValue2()
      {
         return "From VBS String Function";
      }
   }
}
 
The DispIDs must be unique in each class or interface (see below) and sould never change. Also the Guids should never change.
By this you can extend your interface and recompile the dll, and old scripts or other applications will still work. It might be not so important for script languages because they usually use late binding by name, but it's the prefered style for .net OLE interop.
 
It would be even better to extract all methods and properties in a separate interface:
 
using System;
using System.Runtime.InteropServices;
namespace MyDLL
{
   [ComVisible(true)]
   [Guid("B99400F6-4EE0-4D2C-920D-B51C7F626C6E")]
   public interface IOperations
   {
      [DispId(0)]
      string getValue1(string sParameter);
 
      [DispId(1)]
      string getValue2();
   }
 
   [ComVisible(true)]
   [Guid("282A7142-F792-4CC8-AAF9-4558128EAE75")]
   public class Operations : IOperations
   {
      public string getValue1(string sParameter)
      {
         switch (sParameter)
         {
            case "a":
               return "A was chosen";
 
            case "b":
               return "B was chosen";
 
            case "c":
               return "C was chosen";
 
            default:
               return "Other";
         }
      }
      
      public string getValue2()
      {
         return "From VBS String Function";
      }
   }
}
 
You can define as many interfaces for different classes as you want and you can use these interfaces as paramterers.
The ComVisible and Guid attribute needs anly be added to the interfaces, and to classes which must be instanciated diretly from the script language.
GeneralRe: Improovements for your codememberRaymund Macaalay13 Oct '10 - 9:18 
Thanks for the tip!
GeneralIntellisensememberJohan197416 Jul '10 - 0:22 
Good article,
 
Only thing is in VBScript i can not see the methods after the point.
How can i activate intellisense or is this not possible in vbscript.
 
Thanks!
 
Johan
GeneralRe: IntellisensememberRaymund Macaalay17 Jul '10 - 21:50 
Try to use VBS Edit, that a good tool for VBS Programming. It has intellisense
Questionother types?memberpeterbacsi10 May '10 - 22:24 
hi Raymund,
 
(how) can i pass/return other types than string?
 
thx: f.peter
AnswerRe: other types?memberRaymund Macaalay10 May '10 - 23:06 
Sure you can as long as it has the same type counterpart on VBScript.
GeneralThanks a lotmemberIrwan Hassan10 May '10 - 17:29 
Hi, I'm a heavy VBScript user for some of my client application. I really wanted to get the .net to work on VBScript. I will try your example and if it works, I will be very thankful to you.
 
Good Job.
GeneralNice!memberMatt McKinney6 May '10 - 7:29 
Thank you Big Grin | :-D I've been wondering how to do this for some time. 5 from me
Matt McKinney

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 12 Oct 2010
Article Copyright 2010 by Raymund Macaalay
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid