Question

I have a VBA script per mail item for ThisOutlookSession and ignoring the irrelevant parts of the code to my current problem, I am calling the following function:

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

I call this function and test if it returns True or False accordingly:

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

However, when the function is called the MsgBox shows it is setting True but then the other MsgBox shows the function is setting False. Perhaps the problem is the line WriteBatFile = True?

Of course, the Shell command is never run. I would like your help showing me why?

Thank you.

Was it helpful?

Solution 2

My thought is that the error_handle label is always being reached. You need to exit the function after the successful code has been run. Add Exit Function after WriteBatFile = True

OTHER TIPS

Your err_handle is just a lable statement, all it does is tell the compiler that line X is called err_handle for GoTo statements. There is nothing keeping the code from just chugging right through it. The best way to fix your issue is to move the line Exit Function to right after you set WriteBatFile to True. So the fixed code will look like this:

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

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

In err_handle after WriteBatFile is set to False, the program will exit the function natrually when it gets to the End Function. I hope this helps!

if there isn't an error the code will make the WriteBatFile equal true, then make it false.

 WriteBatFile = True

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

it may be better to do something like

If err.number <> 0 then

    WriteBatFile = False

Else

   WriteBatFile = True

End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top