VBA各項雜項筆記
● Q. VBA呼叫C#執行檔(.exe),遇到參數有空白的情形,會導致錯誤,因為此參數被判斷為兩個參數,如何避免此參數被視為兩個參數?
● A. 假設要呼叫一個C#執行檔,第二個參數是一檔案的路徑,而這個檔案路徑可能會有空白,這時可以將參數用「雙引號」包起來,此參數就不會被程式判定成兩個參數,程式碼如下:
'VBA端
'
Private Function fu_excuteCheckExe() As String
Dim errMsg As String
Dim ExePath As String
Dim user_id As String
Dim file_path As String
ExePath = "C:\Consult\Exe_File\Check.exe"
user_id = Environ$("username")
'excute local check.exe
cmd = ExePath & " " & user_id & " " & """" & file_path & """"
cmdReturn = ShellRun(cmd)
'get new file path
If (InStr(cmdReturn, "[Succeed]") = 0) Then
'執行失敗
errMsg = Mid(cmdReturn, InStr(cmdReturn, "[Error]")) '取得[Error](含)之後的字串
GoTo laErr
End If
laErr:
If errMsg <> "" Then fu_excuteCheckExe= "fu_excuteCheckExe():fail " & errMsg
End Function
'Run a shell command, returning the output as a string'
Public Function ShellRun(sCmd As String) As String
Dim oShell As Object
Dim oExec As Object
Dim oOutput As Object
Dim s As String
Dim sLine As String
Set oShell = CreateObject("WScript.Shell")
'run command'
Set oExec = oShell.Exec(sCmd)
Set oOutput = oExec.StdOut
'handle the results as they are written to and read from the StdOut object'
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend
ShellRun = s
Set oShell = Nothing
Set oExec = Nothing
Set oOutput = Nothing
End Function//C# 執行檔
if (args.Length != 2)
{
Console.WriteLine("[Error]Missing or extra some arguments.");
return;
}
else
{
Console.WriteLine("user_id=" + args[0]);
Console.WriteLine("file_path=" + args[1]);
}