Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function always returns False. Why?

Tags:

vba

outlook

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.

like image 570
uncle-junky Avatar asked May 08 '14 14:05

uncle-junky


1 Answers

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!

like image 198
Telestia Avatar answered Sep 27 '22 01:09

Telestia