【转】VB控件和对象:ScriptControl 控件

3. ScriptControl 控件

Microsoft Script Control 控件可以创建运行任何 ActiveX(R) scripting 引擎,例如 Microsoft(R) Visual Basic (R) Scripting Edition 或Microsoft(R) JScript(TM) 的应用程序。简单的的说,可以在程序运行期间,允许用户编写代码并执行代码,计算带变量的的表达式等。

■运行时设置程序代码:

'▲显式创建,勾选引用(不选部件) Microsoft Script Control

Private Sub Command1_Click()

Dim strProgram As String, sc As ScriptControl

'编写代码

strProgram = "Sub My1" & vbCrLf & _

"MsgBox ""运行时设置代码"" ,vbInformation,""我的代码""" & vbCrLf & _

"End Sub"

'设置代码语言,并将代码添加到 ScriptControl

Set sc = CreateObject("ScriptControl")

sc.Language = "VBScript"

sc.AddCode strProgram

'运行代码

sc.Run "My1"

End Sub

'▲隐式创建,不勾选部件和应用

Private Sub Command1_Click()

Dim strProgram As String, sc

'编写代码

strProgram = "Sub My1" & vbCrLf & _

"MsgBox ""运行时设置代码"" ,vbInformation,""我的代码""" & vbCrLf & _

"End Sub"

'设置代码语言,并将代码添加到 ScriptControl

Set sc = CreateObject("ScriptControl")

sc.Language = "VBScript"

sc.AddCode strProgram

'运行代码

sc.Run "My1"

End Sub

'▲使用控件,勾选部件 Microsoft Script Control,并向窗体添加控件 ScriptControl1

Private Sub Command1_Click()

Dim strProgram As String

'编写代码

strProgram = "Sub My1" & vbCrLf & _

"MsgBox ""运行时设置代码"" ,vbInformation,""我的代码""" & vbCrLf & _

"End Sub"

'设置代码语言,并将代码添加到 ScriptControl

ScriptControl1.Language = "VBScript"

ScriptControl1.AddCode strProgram

'运行代码

ScriptControl1.Run "My1"

End Sub

■Script的模块与过程

'▲添加一个模块,默认只有一个模块:Global

ScriptControl1.Modules.Add "Modu2"

'▲在模块 1 中添加过程代码,

'注意 Script 变量定义不能指定类型, dim a as long 会出错

nStr="dim a" & vbCrLf & _

"Function MyFun(x,y)" & vbCrLf & _

" a=a+1 " & vbCrLf & _

" MsgBox ""a="" & a & "" x+y="" & x+y,vbInformation,""运行时设置代码""" & vbCrLf & _

" My1=a" & vbCrLf & _

"End Function"

ScriptControl1.Modules(1).AddCode nStr

'▲调用有返回值的函数

d = ScriptControl1.Modules(1).Run(MyFun, 1, 2) '运行代码

'▲列出所有模块名称

Dim I As Long

List1.Clear

For I = 1 To ScriptControl1.Modules.Count

List1.AddItem ScriptControl1.Modules(I).Name

Next

'▲列出模块 M 的所有过程名称

Dim I As Long,M as long

List2.Clear

M=1

For I = 1 To ctSc.Modules(M).Procedures.Count

List2.AddItem ctSc.Modules(M).Procedures(I).Name

Next

End Sub

■计算带变量的表达式

Private Sub Command1_Click()

'执行一条 scripting 语句例子

x = 10

ScriptControl1.ExecuteStatement "x=" & x '执行一条 scripting 语句,将值 10 赋给变量 x

S = ScriptControl1.Eval("(x-1)^2")

MsgBox S

End Sub

■错误通告

Private Function ErrInf() As String

ErrInf = ScriptControl1.Language & " 语法错误:行 " & ScriptControl1.Error.Line & ",列 " & ScriptControl1.Error.Column & vbCrLf & vbCrLf & _

"错误号:" & ScriptControl1.Error.Number & "," & ScriptControl1.Error.Description

End Function

■ScriptControl 控件的语句使用 VBScript 语法,