Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a .vbs script from Excel VBA

Tags:

vbscript

Is it possible to call a .vbs script from a VBA code whenever needed? If possible then can you give me a sample code of how to do so?

like image 727
Arup Rakshit Avatar asked Oct 30 '12 05:10

Arup Rakshit


People also ask

How do you execute VBS file from Excel macro?

To run the macro from Excel, open the workbook, and press ALT + F8 to display the Run Macro Dialog. Double Click the macro's name to Run it.

How do I open a VBS file in Excel?

The easiest way to open the Visual Basic editor is to use the keyboard shortcut – ALT + F11 (hold the ALT key and press the F11 key). As soon as you do this, it will open a separate window for the Visual Basic editor.


2 Answers

To run a file:

Shell "wscript c:\null\a.vbs", vbNormalFocus

replacing wscript with cscript if the VBS wants to use the console.

Or you can add a reference to the Microsoft Script Control and interact with the VBScript runtime directly to execute VBS code, procedures etc;

Dim scr As ScriptControl: Set scr = New ScriptControl
scr.Language = "VBScript"
scr.AddCode "sub T: msgbox ""All Hail Cthulhu"": end sub"
scr.Run "T"
like image 123
Alex K. Avatar answered Sep 19 '22 12:09

Alex K.


I only want to add to Alex' answer, that in some environments the object must be created in the following way:

set scr = CreateObject("MSScriptControl.ScriptControl")

If Alex adds this to his answer, I will delete this one.

like image 22
Jarekczek Avatar answered Sep 21 '22 12:09

Jarekczek