1

Is it possible to loop a function until an item = TRUE?

I am trying to ping a server... Once connection is established, or Ping = TRUE, then a program will execute. If connection is not established, then the ping will repeat until it is TRUE.

My code thus far is below. If TRUE, MyProgram will open. If False, the function will be called again. But this does not occur...actually nothing occurs, it just exits.

Any help is gladly appreciated. If anyone knows a more efficient way of completing this task, then please let me know. Thank you!

     Function Ping
        Dim oPing, oRetStatus, bReturn
        Set oPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_PingStatus where address='" & "strHost" & "'")

        For Each oRetStatus In oPing
            If IsNull(oRetStatus.StatusCode) Or oRetStatus.StatusCode <> 0 Then
                bReturn = False
            Else
                bReturn = True
            End If
            Set oRetStatus = Nothing
        Next
        Set oPing = Nothing

    Ping = bReturn
    End Function

If Ping Then
    Call MyProgram
Else
    Call PingSub
End If

Sub MyProgram
    Dim objShell
        Set objShell = WScript.CreateObject( "WScript.Shell" )
        objShell.Run("\\Path\To\My\Program.exe")
        Set objShell = Nothing
End Sub

Sub PingSub
    Call Ping
End Sub
crlic306
  • 35
  • 5

2 Answers2

5

Try like this :

Option Explicit
Dim MyLoop,strComputer,objPing,objStatus
MyLoop = True
While MyLoop = True
    strComputer = "smtp.gmail.com"
    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}!\\").ExecQuery _
    ("select * from Win32_PingStatus where address = '" & strComputer & "'")
    For Each objStatus in objPing
        If objStatus.Statuscode = 0 Then
            MyLoop = False
            Call MyProgram()
            wscript.quit
        End If
    Next
    Pause(10) 'To sleep for 10 secondes
Wend
'**********************************************************************************************
 Sub Pause(NSeconds)
    Wscript.Sleep(NSeconds*1000)
 End Sub
'**********************************************************************************************
Sub MyProgram()
Dim objShell
Set objShell = CreateObject( "WScript.Shell" )
objShell.Run("calc.exe")
Set objShell = Nothing
End Sub
'**********************************************************************************************
Hackoo
  • 18,337
  • 3
  • 40
  • 70
  • Nice! Great approach Hackoo! I'll test out tomorrow and post my results. Thank you! – crlic306 Mar 05 '15 at 00:11
  • BRAVO Hackoo! Works flawlessly! I'm so happy, I got the president himself to applaud your great work:[http://media.giphy.com/media/10spcFioEOY7zG/giphy.gif] Lol. Thanks again! – crlic306 Mar 05 '15 at 13:31
0

That would be a recursive function.

https://msdn.microsoft.com/en-us/library/81tad23s.aspx I assume you are using VBA

here is an example from MS

Marco
  • 41
  • 4