VBA中的MS脚本控制

时间:2011-12-09 17:47:54

标签: vb.net vba vbscript

我通常使用VB.Net进行编程,但我已被委托给一个VBA项目,该项目将受益于使用脚本控制来运行脚本。这是示例代码,但在.Run代码行中出错。我可以在VB.Net中轻松完成此操作,但无法在vba中使用它。

错误=参数数量错误或属性无效

Option Explicit
Dim sc As New ScriptControl

Sub RunFunctions()
    MsgBox (Eval("2 * PI"))
End Sub

Function Eval(expr As String) As Object
    Dim code As String
    code = "Dim PI" & vbCrLf & _
           "PI = 3.1416" & vbCrLf & _
           " " & vbCrLf & _
           "Function Result" & vbCrLf & _
           "    Result = " & expr & vbCrLf & _
           "End Function"

    sc.Language = "VBScript"
    sc.AllowUI = True
    sc.AddCode (code)
    Dim myparams() as variant

    Eval = sc.Run("Result", myparams)

End Function

使用脚本控制对象中的.Eval函数在vba中运行正常,但不运行脚本。这是一个例子,如果有人关心......

Sub SimpleTask()
    Dim expr As String
    sc.Language = "VBScript"
    expr = "2 + 2 * 50"
    MsgBox sc.Eval(expr)
End Sub

2 个答案:

答案 0 :(得分:2)

我认为问题在于sc.Run的参数。尝试从

更改此调用
Eval = sc.Run("Result", myparams)

Eval = sc.Run("Result")

<强>更新

这是一个完整的表单,使用您的代码编译并正确运行:

Option Explicit On
Option Strict On

Imports MSScriptControl

Public Class Form1

    Dim sc As New ScriptControl

    Sub RunFunctions()
        MsgBox(Eval("2 * PI"))
    End Sub

    Function Eval(expr As String) As Object
        Dim code As String
        code = "Dim PI" & vbCrLf & _
               "PI = 3.1416" & vbCrLf & _
               " " & vbCrLf & _
               "Function Result" & vbCrLf & _
               "    Result = " & expr & vbCrLf & _
               "End Function"

        sc.Language = "VBScript"
        sc.AllowUI = True
        sc.AddCode(code)
        Dim myparams() As Object

        Eval = sc.Run("Result")

    End Function
    Sub SimpleTask()
        Dim expr As String
        sc.Language = "VBScript"
        expr = "2 + 2 * 50"
        MsgBox(sc.Eval(expr))
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        SimpleTask()
        RunFunctions()
    End Sub
End Class

答案 1 :(得分:1)

这是VBA的最终工作代码。 competent_tech有一个用于VB.Net。

Option Explicit
Dim sc As New ScriptControl

Sub RunFunctions()
    MsgBox (Eval("2 * PI"))
End Sub

Function Eval(expr As String) As String
    Dim code As String
    code = "Dim PI" & vbCrLf & _
           "PI = 3.1416" & vbCrLf & _
           " " & vbCrLf & _
           "Function Result" & vbCrLf & _
           "    Result = " & expr & vbCrLf & _
           "End Function"

    sc.Language = "VBScript"
    sc.AllowUI = True
    sc.AddCode (code)

    Eval = sc.Run("Result")

End Function