【发布时间】:2020-11-25 13:20:13
【问题描述】:
我需要将 java 函数的输出字符串放入我的 VBA 项目中。作为一个快速示例,我试图获取安装的 java 版本的输出,但在实际应用程序中它将是其他私有函数。
第一次尝试:
' Needs a reference to Windows Script Host Object Model
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub get_java_output()
Dim cmd_windows As New WshShell
Dim execution_cmd As WshExec
Dim command_str As String
command_str = "java -version"
Set execution_cmd = cmd_windows.exec("cmd.exe /c " & command_str)
Do While execution_cmd.Status = WshRunning
Sleep 20
Loop
final_string = execution_cmd.StdOut.ReadAll
Debug.Print final_string
End Sub
第二次尝试:
Sub get_java_output_2()
Dim windows_shell As Object
Set windows_shell = CreateObject("WScript.Shell")
command_str = "java -version"
shell_output = windows_shell.Run("cmd /c " & command_str & " > c:\temp\output.txt", 0, False)
Set fso = CreateObject("Scripting.FileSystemObject")
Set File = fso.OpenTextFile("c:\temp\output.txt", 1)
final_string = File.ReadAll
File.Close
Debug.Print final_string
End Sub
它们都不适合我。
我想避免在我的第二次尝试示例中使用临时文件。在最终的使用中,我会调用这个函数几十万次,我不希望创建那么多文件或编辑那个文件那么多次......
【问题讨论】:
-
这实际上与 Java 本身无关。您正在尝试捕获通过 shell 命令调用的进程的输出。也许这里的答案之一可能会对您有所帮助:stackoverflow.com/questions/2784367/…