新建From1(窗体),新建Command1(按钮CommandButton),代码:
Private Sub s_ExecuteCommandAndGetOutput(command As String)
Dim tempFile As String
Dim fileNumber As Integer
Dim commandOutput As String
' 创建一个临时文件名
tempFile = App.Path & "\tempfile.txt"
' 打开文件用于输出重定向
fileNumber = FreeFile()
Open tempFile For Output As #fileNumber
' 使用管道将命令的输出重定向到文件
Shell "cmd /c " & command & " > " & tempFile, vbHide
' 关闭文件
Close #fileNumber
' 读取文件内容获取命令输出
Open tempFile For Input As #fileNumber
While Not EOF(fileNumber)
Line Input #fileNumber, commandOutput
' 处理输出或者存储起来用于后续处理
Debug.Print commandOutput
Wend
Close #fileNumber
MsgBox "结果在 " & tempFile, vbInformation, "成功"
' 删除临时文件
'Kill tempFile
End Sub
Private Sub Command1_Click()
Dim strCmd As String
strCmd = "dir *.*"
Call s_ExecuteCommandAndGetOutput(strCmd)
End Sub