Loop a function?

陌路散爱 提交于 2019-11-27 08:28:52

问题


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

回答1:


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
'**********************************************************************************************



回答2:


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



来源:https://stackoverflow.com/questions/28865002/loop-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!