关于vb 执行 txt文件中的代码问题

2025-03-25 09:55:07
推荐回答(3个)
回答1:

txt文件中不要用vb语句,这样处理会简单的多。例如1.txt 文件中是这些内容:

[Combo1]
1
2
3

[Text1]
abc

[Command1]
退出
Private Sub Form_Load()
  Dim s As String, c As String, ctl As Control
  
    Open App.Path & "\1.txt" For Input As #1
    Do While Not EOF(1)
      Line Input #1, s
      If Left(s, 1) = "[" Then
        c = Mid(s, 2, InStrRev(s, "]") - 2)
        Set ctl = Nothing
        For Each ctl In Me.Controls
          If ctl.Name = c Then
            Exit For
          End If
        Next
      Else
        If Trim(s) <> "" And Not (ctl Is Nothing) Then
          If TypeOf ctl Is TextBox Then
            ctl.Text = s
          ElseIf TypeOf ctl Is ComboBox Or TypeOf ctl Is ListBox Then
            ctl.AddItem s
          ElseIf TypeOf ctl Is CommandButton Or TypeOf ctl Is Label Then
            ctl.Caption = s
          End If
        End If
      End If
    Loop
    Close #1
    
End Sub

回答2:



Private Sub Form_Load()
Dim tmp As String
Open App.Path & "\1.txt" For Input As #1
Do While Not EOF(1)
Line Input #1, tmp
Combo1.AddItem tmp
Loop
Close #1
End Sub

'你只要在程序同目录下的1.txt文件里 按行写下要添加到combo下拉列表的内容即可

回答3:

'执行代码需要调用API:
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

'读取txt单行嵌入执行代码
ExecuteLine stext