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

利用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

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

你可能感兴趣的:(sql,ide,VBScript,vb,VB.NET)