VBA 中的 MS 脚本控件 [英] MS Script Control in VBA

查看:21
本文介绍了VBA 中的 MS 脚本控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I generally use VB.Net for programming but I have been delegated to a VBA project that would benefit from using script control for running script. Here is sample code but errors out on the .Run line of code. I can do this in VB.Net easy but can't get it to work in vba.

ERROR = 错误数量的参数或无效的属性赋值

ERROR = Wrong number of arguments or invalid property assignent

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 中运行正常,但不运行脚本.这是一个例子,如果有人想知道...

Using the .Eval function from the script control object runs ok in vba but does not run scripts. Here is an example of that if someone cares to know...

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

推荐答案

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

Here is the final working code for VBA. competent_tech has one for 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

这篇关于VBA 中的 MS 脚本控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆