函数始终返回False.为什么?

unc*_*nky 4 vba outlook-vba

我为每个邮件项目都有一个VBA脚本,ThisOutlookSession并忽略了代码中与我当前问题无关的部分,我调用了以下函数:

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
Run Code Online (Sandbox Code Playgroud)

我调用此函数并测试它是否返回TrueFalse相应:

result = WriteBatFile(match.Value)
    If result = True Then
        retval = Shell("""C:\Program Files (x86)\PuTTY\plink.exe"" -ssh ME@MYSERVER -m C:\Users\ME\Desktop\runThese.bat", vbNormalFocus)
    End If
Run Code Online (Sandbox Code Playgroud)

但是,当该功能被调用时,MsgBox它正在设置,True但是另一个MsgBox显示该功能正在设置False.也许这个问题就行了WriteBatFile = True

当然,Shell命令永远不会运行.我希望你的帮助告诉我为什么?

谢谢.

Tel*_*tia 5

err_handle只是一个简单的语句,它所做的只是告诉编译器err_handleGoTo语句调用行X. 没有什么能阻止代码直接通过它.解决问题的最佳方法是Exit Function在设置WriteBatFile为True 后将行移至右侧.所以固定代码看起来像这样:

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

err_handle:
    'MsgBox "Setting false. Code: "
    WriteBatFile = False
End Function
Run Code Online (Sandbox Code Playgroud)

err_handleafter WriteBatFile设置为False后,程序将在到达时自动退出函数End Function.我希望这有帮助!


ror*_*.ap 2

我的想法是,error_handle标签总是被触及的。成功运行代码后,您需要退出该函数。添加Exit FunctionWriteBatFile = True