รับเอาต์พุตของสตริง Java จาก VBA
ฉันต้องการรับสตริงเอาต์พุตของฟังก์ชัน 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 ที่แสดงบนเชลล์คำสั่งจะถือว่าเป็นข้อผิดพลาดดังนั้นจึงไม่ใช่ผลลัพธ์ ข้อสงสัยได้รับการแก้ไขแล้วที่นี่
ในกรณีของการส่งผลผลิต Java ไปยังไฟล์นั้นจะถูกแก้ไขได้โดยใช้2>แทนเพียงแค่>มันเป็นกล่าวที่นี่ อย่างไรก็ตามมีหลายรูปแบบที่แตกต่างกันขึ้นอยู่กับสิ่งที่คุณต้องการตามที่รายงานในลิงค์อื่นนี้ ปัญหาเล็กน้อยของวิธีนี้คือการสร้างไฟล์เอาต์พุตต้องใช้เวลาในการดำเนินการดังนั้นตัวแปรสุดท้ายของRunคำสั่งจะต้องถูกตัดสินเป็นTrue
และรหัสมีดังนี้:
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 & " 2> c:\temp\output.txt", 0, True)
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 โดยตรงไปยังตัวแปรจะแก้ไขได้โดยใช้StdErrแทนStdOut. ฉันได้รับไฟส่องสว่างอ่านลิงค์นี้ WshExecวัตถุมีสามองค์ประกอบหลัก: StdErr, และStdIn StdOutหากสตริงเอาต์พุต java ถือว่าเป็นข้อผิดพลาดควรอยู่ภายในStdErrแทน
และรหัสมีดังนี้:
' 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(command_str)
Do While execution_cmd.Status = WshRunning
Sleep 20
Loop
final_string = execution_cmd.StdErr.ReadAll
Debug.Print final_string
End Sub