2014-05-08 163 views
4

我有ThisOutlookSession每個郵件項目中的VBA腳本,並忽略代碼無關的部分,以我目前的問題,我打電話以下功能:函數總是返回False。爲什麼?

Function WriteBatFile(inVar As String) As Boolean 
On Error GoTo err_handle: 

    Dim sFile As String 
    sFile = "C:\Users\ME\Desktop\myScript.bat" 

    Dim fso As Object 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    Dim oFile As Object 
    Set oFile = fso.CreateTextFile(sFile) 

    oFile.WriteLine "sleep 2" 
    oFile.WriteLine "./myScript.sh " & inVar 
    oFile.WriteLine "exit" 
    oFile.Close 

    Set fso = Nothing 
    Set oFile = Nothing 

    'MsgBox "Setting True", vbInformation 
    WriteBatFile = True 

err_handle: 
    'MsgBox "Setting false. Code: " 
    WriteBatFile = False 
    Exit Function 
End Function 

我調用這個函數,並測試它是否返回TrueFalse相應:

result = WriteBatFile(match.Value) 
    If result = True Then 
     retval = Shell("""C:\Program Files (x86)\PuTTY\plink.exe"" -ssh [email protected] -m C:\Users\ME\Desktop\runThese.bat", vbNormalFocus) 
    End If 

然而,當功能被稱爲MsgBox顯示它是設置True但隨後其他MsgBox示出的功能被設置False。也許問題是行WriteBatFile = True

當然,Shell命令從不運行。我希望你的幫助告訴我爲什麼?

謝謝。

回答

1

我的想法是error_handle標籤總是到達。成功的代碼運行後,您需要退出該功能。添加Exit FunctionWriteBatFile = True

+0

沒有錯誤 - 他的代碼在錯誤處理程序之前從不退出函數。 – xxbbcc

+1

@叔叔 - 垃圾 - 是的。 –

0

如果沒有錯誤代碼將使WriteBatFile等於true,然後使其爲false。

WriteBatFile = True 

err_handle: 
    'MsgBox "Setting false. Code: " 
    WriteBatFile = False 

它可能是更好的做這樣的事情

If err.number <> 0 then 

    WriteBatFile = False 

Else 

    WriteBatFile = True 

End If 
+0

通過正確退出函數避免錯誤0不是更好嗎? – RubberDuck

5

err_handle只是一個拉布勒聲明,它的作用是告訴大家,行X編譯器被稱爲err_handleGoTo語句。沒有任何東西能夠讓代碼不會通過它而直接進入。解決問題的最佳方法是在將WriteBatFile設置爲True後,將行Exit Function移至右側。因此,固定的代碼看起來就像這樣:WriteBatFile設置爲False在err_handle

'MsgBox "Setting True", vbInformation 
WriteBatFile = True 
Exit Function 

err_handle: 
    'MsgBox "Setting false. Code: " 
    WriteBatFile = False 
End Function 

,程序將退出功能自然地當它到達的End Function。我希望這有幫助!

+0

到目前爲止,這是迄今爲止這個問題的最佳答案,其他人都沒有真正解決根本原因(錯誤處理程序是一個標籤,並且除非在它之前放置了「Exit Function」或「Exit Sub」 。 – enderland

相關問題