Link to home
Start Free TrialLog in
Avatar of PatrickO
PatrickO

asked on

How to execute a string using VB?

I'm making a program to build "ON-LINE" VB commands... all of these are saved in a DB.
When the program reads a record, the command is stored in a variable. for example:

dim comd as string
..
..
Text1.text="02-12-1998"

comd=rs("COMMAND")  ' reading the DB   COMMAND="FORMAT(CDATE(Text1.text),"MM/DD/YYYY")"
..
..
at last comd should have 02/12/1998

How to execute the command stored in comd and get the right date. I really appreciate your comments.
Thanks a lot
Patrick

Avatar of aelatik
aelatik
Flag of Netherlands image

Impossible. In VB you have to assign the database results to a variable which VB reads as a variable and not as part of the code.

VB cannot use functions or code stored in a database.
Including external code or function(s) isn't available either !

Avatar of Metalhead
Metalhead


  VB is a compiled language so I don't see how you could do this.

  Have you thought about reading your variable information then creating a vbscript object on the fly and executing that?

I think you have to write a parser to do that....but I think it is too complicated.  Not sure how you could do that at this point.
From the Project menu, select "References" and add "Microsoft Script Control 1.0". Add Command Button "Command1" to your form and paste this into your code:


Private Sub Command1_Click()
Dim S As String
Dim oSC As ScriptControl
Dim iVal
Dim toexe As String
    Set oSC = New ScriptControl
    oSC.Language = "VBScript"
    toexe = "FormatDateTime(" & S & ", vbLongDate)"
    iVal = oSC.Eval(toexe)
    MsgBox iVal, vbOKOnly, "Value of iVal"
End Sub


Nothing will execute VB Code but this will execute VBA code.

Regards
Sorry.. I forgot a line
Here is the correct code:

Private Sub Command1_Click()
Dim S As String
Dim oSC As ScriptControl
Dim iVal
Dim toexe As String
    S = "02-12-1998"
    Set oSC = New ScriptControl
    oSC.Language = "VBScript"
    toexe = "FormatDateTime(" & S & ", vbLongDate)"
    iVal = oSC.Eval(toexe)
    MsgBox iVal, vbOKOnly, "Value of iVal"
End Sub
ASKER CERTIFIED SOLUTION
Avatar of emadat
emadat
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
e.g.

Private Function InterpreteCmd(cmd As String) As Variant
    Dim i As Long
    Dim j As Long
    Dim str As String
    Dim valVar As Variant

    If (InStr(1, cmd, "Format(")) Then
        i = InStr(1, cmd, "Format(") + 7
        j = InStr(i + 1, cmd, ",")
        valVar = InterpreteCmd(Mid(cmd, i + 1, j - i - 1))
        i = InStr(j, cmd, """")
        j = InStr(i + 1, cmd, """")
        str = Mid(cmd, i + 1, j - i - 1)
        InterpreteCmd = Format(valVar, str)
    Else
        InterpreteCmd = cmd
    End If
End Function

InterpreteCmd("Format(22-10-76, ""mm/dd/yyyy"")")
' return value "22/10/1976"

Nice answer emadat, you beat me to it. (all that typing for nothing ;) )  May I also add, that the Script Control is a very powerful tool and suggest that anyone who doesn't know about it go out and learn.
use script, but not simply use Eval()

    Dim objScript As Object
    Dim sCode As String
    Dim comd As String
   
    strCode = "Function comd()" & vbNewLine & _
            "comd = " & rs("COMMAND") & vbNewLine & _
            "End Function"
    Set objScript = CreateObject("MSScriptControl.ScriptControl")
    objScript.Language = "VBScript"
    objScript.addObject "Text1", Text1 'Add any object will used by COMMAND
    objScript.AddCode strCode
    comd = objScript.Run("comd")
Weel, if you have VB6, you might use the indirect function call CallByName().
This function would not help in this matter.

According to MSDN:

The CallByName is a function theat executes a method of an object, or sets or returns a property of anobject.

And here are its remarks:

The CallByName function is used to get or set a property, or invoke a method at run time using a string name.

In the following example, the first line uses CallByName to set the MousePointer property of a text box, the second line gets the value of the MousePointer property, and the third line invokes the Move method to move the text box:

CallByName Text1, "MousePointer", vbLet, vbCrosshair
Result = CallByName (Text1, "MousePointer", vbGet)
CallByName Text1, "Move", vbMethod, 100, 100

<b>Regards</b>
Avatar of PatrickO

ASKER

10q guys for all your comments..
I`m going to check one by one..

the best one will receive the points..It`s a deal..

Xanks..
What you are contemplating is a nightmare, and I go along fully with the comments above. However, it IS possible to make VB output vbp and frm files (which are ascii) and then open a new instance of VB and run the newly created project. I'm sure you can even get VB to compile the project and run the exe. I insist that script is the way to go, but for curiosities sake, here's an example of using VB to create VB:

Take a form and add a textbox (Text1) and a commandbutton (Command1). Then add the code below. The idea (kinda obviously)is that you type something into the textbox and hit the commandbutton. When you do this, VB writes a vbp project file and a frm form file to a given directory, and then opens it in VB. The newly created project contains a commandbutton, which, when you click it, will display the message you typed in to the textbox in the creator project.

Kindest regards,
Rhaedes

'API to open the newly created VB project
Private Declare Function ShellExecute Lib "shell32" _
   Alias "ShellExecuteA" _
  (ByVal hwnd As Long, _
   ByVal lpOperation As String, _
   ByVal lpFile As String, _
   ByVal lpParameters As String, _
   ByVal lpDirectory As String, _
   ByVal nShowCmd As Long) As Long
   
Private Const SW_SHOWNORMAL As Long = 1
Private Const SW_SHOWMAXIMIZED As Long = 3
Private Const SW_SHOWDEFAULT As Long = 10
Private Const SE_ERR_NOASSOC As Long = 31


Dim myPath As String
Dim myMessage As String


Private Sub Command1_Click()

'Change to where you want to store the project
myPath = "c:\WHEREVER\"
Open myPath & "Project1.vbp" For Output As #1
Print #1, "Type=Exe"
Print #1, "Form=Form1.frm"
Print #1, "Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\SYSTEM\stdole2.tlb#OLE Automation"
Print #1, "Startup=""Form1"""
Print #1, "Command32="""""
Print #1, "Name=""Project1"""
Print #1, "HelpContextID=""0"""
Print #1, "CompatibleMode=""0"""
Print #1, "MajorVer=1"
Print #1, "MinorVer=0"
Print #1, "RevisionVer=0"
Print #1, "AutoIncrementVer=0"
Print #1, "ServerSupportFiles=0"
Print #1, "CompilationType=0"
Print #1, "OptimizationType=0"
Print #1, "FavorPentiumPro(tm)=0"
Print #1, "CodeViewDebugInfo=0"
Print #1, "NoAliasing=0"
Print #1, "BoundsCheck=0"
Print #1, "OverflowCheck=0"
Print #1, "FlPointCheck=0"
Print #1, "FDIVCheck=0"
Print #1, "UnroundedFP=0"
Print #1, "StartMode=0"
Print #1, "Unattended=0"
Print #1, "Retained=0"
Print #1, "ThreadPerObject=0"
Print #1, "MaxNumberOfThreads=1"
Close #1

Open myPath & "Form1.frm" For Output As #2
Print #2, "VERSION 5.00"
Print #2, "Begin VB.Form Form1"
Print #2, "   Caption=""Form1"""
Print #2, "   ClientHeight=3195"
Print #2, "   ClientLeft=60"
Print #2, "   ClientTop=345"
Print #2, "   ClientWidth=4680"
Print #2, "   LinkTopic=""Form1"""
Print #2, "   ScaleHeight=3195"
Print #2, "   ScaleWidth=4680"
Print #2, "   StartUpPosition=3    'Windows Default"
Print #2, "   Begin VB.CommandButton Command1"
Print #2, "      Caption=""Click Me!"""
Print #2, "      Height=855"
Print #2, "      Left=600"
Print #2, "      TabIndex=0"
Print #2, "      Top=720"
Print #2, "      Width=1935"
Print #2, "   End"
Print #2, "End"
Print #2, "Attribute VB_Name=""Form1"""
Print #2, "Attribute VB_GlobalNameSpace=False"
Print #2, "Attribute VB_Creatable=False"
Print #2, "Attribute VB_PredeclaredId=True"
Print #2, "Attribute VB_Exposed=False"
Print #2, "Private Sub Command1_Click()"
'Add text to msgbox in output program
Print #2, "MsgBox """ & Text1.Text & """"
Print #2, "End Sub"
Close #2

'The new Project is now created
'To open it in VB use:
allPath = myPath & "Project1.vbp"
Call ShellExecute(0&, "open", allPath, 0&, 0&, SW_SHOWNORMAL)
'Then wait for it to be fully loaded and send F5
'Better still, compile it and shell execute it.


End Sub
I gonna give the points to emadat for the idea to use VBScript Control...

Now, It is  not working very well , but the idea is good.
Thanks a Lot..