|
|
Title | Execute VB Script code at run time |
Description | This example shows how to execute VB Script code at run time in Visual Basic 6. The program uses the MSScriptControl to execute the VBScript code. |
Keywords | VBScript, script |
Categories | Software Engineering |
|
|
Thanks to Ziad Suliman.
When the program loads, it creates a MSScriptControl and sets its language to VBScript. It adds the Form1 object to the control with the name "Form1" so the VBScript code can manipulate it. It then sets the form's TextBox to some VBScript code.
|
|
Private Sub Form_Load()
Set VBScript = New MSScriptControl.ScriptControl
'set Language
VBScript.Language = "VBScript"
'Add object
VBScript.AddObject "Form1", Form1
'allowed to display user-interface elements.
VBScript.AllowUI = True
' Example:
'this code: calculate a! , sum from 1 to a ,change
' form backcolor ,change form caption
Text1 = _
"'Programmed by Ziad Suliman" & vbCrLf & _
"'Civil Engineering Tishreen University Syria" & _
vbCrLf & _
"'Email:Eckert@naharnet.com" & vbCrLf & vbCrLf & _
"'This code:" & vbCrLf & _
"' Calculates A!" & vbCrLf & _
"' Calculates the sum from 1 to A" & vbCrLf & _
"' Changes the form's BackColor" & vbCrLf & _
"' Changes the form's Caption" & vbCrLf & vbCrLf _
& _
"a = InputBox(""Number"")" & vbCrLf & _
"factorial = 1" & vbCrLf & _
"sum = 0" & vbCrLf & _
"For i = 1 To a" & vbCrLf & _
" factorial = factorial * i" & vbCrLf & _
" sum = sum + i" & vbCrLf & _
"Next" & vbCrLf & _
"'Display the results." & vbCrLf & _
"MsgBox ""Factorial: "" & factorial & "", Sum: "" & " & _
"sum" & vbCrLf & vbCrLf & _
"'Change the form" & vbCrLf & _
"Form1.Caption = ""Ziad Suliman""" & vbCrLf & _
"Form1.BackColor = vbRed"
End Sub
|
|
When the user clicks the Run Code button, the program adds the code to the VBScript object. The code prompts the user for input and displays the results.
|
|
Private Sub Command1_Click()
'Add code that there is in text1
On Error GoTo line1
VBScript.AddCode Text1
Exit Sub
line1:
MsgBox Err.Number & Err.Description, vbCritical, "error"
Err.Clear
End Sub
|
|
|
|
|
|