5

I have 2 vbs files.

A.vbs:

Class test
  public a
  public b
End Class

B.vbs:

Dim objShell
Set objShell = Wscript.CreateObject("WScript.Shell")
objShell.Run "C:\Users\shanmugavel.chinnago\Desktop\Test3.vbs" 

Dim ins
Set ins = new test 'Here throws "Class not defined: test"
ins.a = 10
ins.b = "SCS"

msgbox ins.a
msgbox ins.b

Now I want to achive this like in B.vbs file. But it throws error while creating instance for the class availble in A.vbs. Any help?

Lumi
  • 14,775
  • 8
  • 59
  • 92
Shan C
  • 87
  • 1
  • 2
  • 11

4 Answers4

8

.Running a .vbs won't make the code usable in another one. A simple but extensible strategy is to use .ExecuteGlobal on the 'libraries'. Given

Lib.vbs:

' Lib.vbs - simple VBScript library/module
' use
'  ExecuteGlobal goFS.OpenTextFile(<PathTo\Lib.vbs>).ReadAll()
' to 'include' Lib.vbs in you main script

Class ToBeAShamedOf
  Public a
  Public b
End Class ' ToBeAShamedOf

and main.vbs:

' main.vbs - demo use of library/module Lib.vbs

' Globals
Dim gsLibDir : gsLibDir = ".\"
Dim goFS     : Set goFS = CreateObject("Scripting.FileSystemObject")

' LibraryInclude
ExecuteGlobal goFS.OpenTextFile(goFS.BuildPath(gsLibDir, "Lib.vbs")).ReadAll()

WScript.Quit main()

Function main()
  Dim o : Set o = New ToBeAShamedOf
  o.a = 4711
  o.b = "whatever"
  WScript.Echo o.a, o.b
  main = 1 ' can't call this a success
End Function ' main

you'll get:

cscript main.vbs
4711 whatever

(cf. this answer for a seed of a useful class)

Community
  • 1
  • 1
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96
3

Your b script doesn't have contact with youyr a script, you need to include the code like so, then you can use code from a like it were present in b

call Include("a.vbs")

Sub Include (Scriptnaam)
  Dim oFile
  Set oFile = oFso.OpenTextFile(Scriptnaam)
  ExecuteGlobal oFile.ReadAll()
  oFile.Close
End Sub
peter
  • 41,770
  • 5
  • 64
  • 108
2

This is the code that we use to do this.

Sub Include(sInstFile)
    Dim f, s, oFSO
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    On Error Resume Next
    If oFSO.FileExists(sInstFile) Then
        Set f = oFSO.OpenTextFile(sInstFile)
        s = f.ReadAll
        f.Close
        ExecuteGlobal s
    End If
    On Error Goto 0
    Set f = Nothing
    Set oFSO = Nothing
End Sub

Include("c:\files\SSDConnection.vbs")
Include("c:\files\SSDTable.vbs")

Works flawless for our team

Jonas Söderström
  • 4,856
  • 2
  • 36
  • 45
1

You can convert B.vbs into a Windows Script File which will allow you to include A.vbs.

Cheran Shunmugavel
  • 8,319
  • 1
  • 33
  • 40