Ping IP Address with VBA code and return results in Excel

excel, vba

Solution

You don't need code for this. Turn all the cells red, then add conditional formatting to make it green when you want.

Home > Conditional Formatting > New Rule > Use a formula...

=C2="Connected"

and format to green. If you want to do it in code, you can add some lines in your For Each loop

If Result = "Connected" Then
    Cell.Offset(0,1).Font.Color = vbGreen
Else
    Cell.Offset(0,1).Font.Color = vbRed
End If

Problem

I have some visual basic code (see below) that tests an IP connection in column B (of an excel spreadsheet) and puts whether or not it is connected or un-reachable in column c, I was just wondering if you could help me I would like it to be green if 'connected', and any other result would be red. Also, could this script be run automatically on an hourly or daily basis? Many Thanks, Andy ``` Function GetPingResult(Host) Dim objPing As Object Dim objStatus As Object Dim strResult As String Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}"). _ ExecQuery("Select * from Win32_PingStatus Where Address = '" & Host & "'") For Each objStatus In objPing Select Case objStatus.StatusCode Case 0: strResult = "Connected" Case 11001: strResult = "Buffer too small" Case 11002: strResult = "Destination net unreachable" Case 11003: strResult = "Destination host unreachable" Case 11004: strResult = "Destination protocol unreachable" Case 11005: strResult = "Destination port unreachable" Case 11006: strResult = "No resources" Case 11007: strResult = "Bad option" Case 11008: strResult = "Hardware error" Case 11009: strResult = "Packet too big" Case 11010: strResult = "Request timed out" Case 11011: strResult = "Bad request" Case 11012: strResult = "Bad route" Case 11013: strResult = "Time-To-Live (TTL) expired transit" Case 11014: strResult = "Time-To-Live (TTL) expired reassembly" Case 11015: strResult = "Parameter problem" Case 11016: strResult = "Source quench" Case 11017: strResult = "Option too big" Case 11018: strResult = "Bad destination" Case 11032: strResult = "Negotiating IPSEC" Case 11050: strResult = "General failure" Case Else: strResult = "Unknown host" End Select GetPingResult = strResult Next Set objPing = Nothing End Function Sub GetIPStatus() Dim Cell As Range Dim ipRng As Range Dim Result As String Dim Wks As Worksheet Set Wks = Worksheets("Sheet1") Set ipRng = Wks.Range("B3") Set RngEnd = Wks.Cells(Rows.Count, ipRng.Column).End(xlUp) Set ipRng = IIf(RngEnd.Row < ipRng.Row, ipRng, Wks.Range(ipRng, RngEnd)) For Each Cell In ipRng Result = GetPingResult(Cell) Cell.Offset(0, 1) = Result Next Cell End Sub ```

Original source