15

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?

2

4 Answers 4

27

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"
Sign up to request clarification or add additional context in comments.

6 Comments

Hi Alex, i want to call a .vbs file from VBA... so how to do that? this was my question..Can you clarify your suggestion please?
Sub test() Dim scr As ScriptControl: Set scr = New ScriptControl scr.Language = "VBScript" scr.AddCode "sub T: msgbox ""All Hail Cthulhu"": end sub" scr.Run "T" End Sub
getting error : Compiler error: "User-defined type not defined"
The shell line runs a vbs ... To avoid User-defined type not defined you must click tools -> references in the VBA IDE & tick Microsoft Script Control 1.0
Alex, would you mind adding one more detail to your answer? That the object may also be created using set scr = CreateObject("MSScriptControl.ScriptControl"), which is the only option in some environments.
|
10

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.

Comments

0

Try somthing like this

ChDir ThisWorkbook.Path
Shell "wscript " & ThisWorkbook.Path & "\your.vbs", vbNormalFocus

It helped me.

Comments

0

You may want to use """ if your path name contains a - For me the following solved this issue:

Shell "cscript """ & ActiveWorkbook.Path & """\your.vbs", vbNormalFocus

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.