下面的代码,我放到了一个CommandButton的click事件里面
为什么在执行:AddCode 的时候提示:语句未结束 错误?
同时我发现:使用ScriptControl执行脚本命令的时候,如果使用
dim a就可以,如果执行dim a as string就有错误,同时发现,如果是单纯的顺序的脚本命令执行没问题,如果有if或者for循环等命令,就会出错,请指教,能否避免这种错误?
    Dim ScriptControl1 As New ScriptControl
    Dim strVBS As String    
    ScriptControl1.Language = "VBScript"
    
    Dim strCode As String
        strCode = "Sub DivideByZero()" & vbCrLf & _
           "Dim prime" & vbCrLf & _
           "Dim k" & vbCrLf & _
           "for k=0 to a.text2.count-1" & vbCrLf & _
               "prime=prime & a.text2(k).text " & vbCrLf & _
           "next k " & vbCrLf & _
           "MsgBox prime " & vbCrLf & _
        "End Sub"
    With ScriptControl1
         .AddObject "a", Me, True
         .AddCode strCode
         .Run "DivideByZero"
    End With

解决方案 »

  1.   

    Private Sub Command1_Click()
        'Dim ScriptControl1 As New ScriptControl
        Dim strVBS As String
        ScriptControl1.Language = "VBScript"
        
        Dim strCode As String
            strCode = "Sub DivideByZero()" & vbCrLf & _
               "Dim prime" & vbCrLf & _
               "Dim k" & vbCrLf & _
               "for k=0 to a.text2.ubound" & vbCrLf & _
                   "prime=prime & a.text2(k).text " & vbCrLf & _
               "next" & vbCrLf & _ '不要k
               "MsgBox prime " & vbCrLf & _
            "End Sub"
        With ScriptControl1
             .AddObject "a", Me, True
             .AddCode strCode
             .Run "DivideByZero"
        End With
    End Sub
      

  2.   

    补充一下:
    ==================================================
    text2()各成员可能不连续
    比如说text2共三个成员分别为text2(0),text2(3),text2(100)
    所以建议用for each
    ===================================================
    Private Sub Command1_Click()
        'Dim ScriptControl1 As New ScriptControl
        Dim strVBS As String
        ScriptControl1.Language = "VBScript"
        
        Dim strCode As String
            strCode = "Sub DivideByZero()" & vbCrLf & _
               "Dim prime" & vbCrLf & _
               "Dim k" & vbCrLf & _
               "for each t in a.text2" & vbCrLf & _
                   "prime=prime & t.text " & vbCrLf & _
               "next" & vbCrLf & _
               "MsgBox prime " & vbCrLf & _
            "End Sub"
        With ScriptControl1
             .AddObject "a", Me, True
             .AddCode strCode
             .Run "DivideByZero"
        End With
    End Sub