综合

img northwolves

如何象SQL语句中的Exec那样在VB中执行一段代码?

发表于2004/10/20 22:59:00  2906人阅读

利用API  引用vb6a.dll  (Private Declare Function EbExecuteLine Lib "vba6.dll" (ByVal pStringToExec As Long, ByVal Unknownn1 As Long, ByVal Unknownn2 As Long, ByVal fCheckOnly As Long) As Long)可以实现字符串命令的执行和字符串表达式的运算(http://blog.csdn.net/northwolves/archive/2004/04/05/19592.aspx),但由于VB6a.dll只能应用于IDE 环境,程序一经编译,必然出错,无法生成可执行文件.
如:

Option Explicit
Private Declare Function EbExecuteLine Lib "vba6.dll" (ByVal pStringToExec As Long, ByVal Unknownn1 As Long, ByVal Unknownn2 As Long, ByVal fCheckOnly As Long) As Long
Private Function ExecuteLine(sCode As String, Optional fCheckOnly As Boolean) As Boolean
    ExecuteLine = EbExecuteLine(StrPtr(sCode), 0&, 0&, Abs(fCheckOnly)) = 0
End Function
Private Sub Command1_Click()
ExecuteLine "dim pi as double"
ExecuteLine "pi= 4*atn(1)"
ExecuteLine "msgbox ""Pi=""& pi"
End Sub


如何解决这个问题,查了许多资料,包括在许多论坛上的讨论,也没能完美解决.个人认为还是ScriptControl控件调用方便些:

Option Explicit
Sub Main()
Dim scr As Object, mysub As String
Set scr = CreateObject("MSScriptControl.ScriptControl")
   mysub = "sub msg()" & vbCrLf
   mysub = mysub & "MsgBox ""今天是"" & WeekdayName(Weekday(Date)) & ""!"", vbOKCancel + vbInformation, ""提示"""
   mysub = mysub & vbCrLf & "end sub "
   scr.Language = "vbscript"
   scr.AddCode mysub
   scr.ExecuteStatement "msg"
   Set scr = Nothing
End Sub

上述代码在编译前后都能正确运行.

阅读全文
0 0

相关文章推荐

img
取 消
img