Problem : How do I return Hostname in excel cell by pinging IP address (VBA)

Problem : How do I return Hostname in excel cell by pinging IP address (VBA)

I have a spreadsheet that has range of IP addresses in column A and hostnames in Column B. not all IP addresses are assigned, so some of the column B is empty. I want to be able to ping IP in column A and check if it’s assigned. If it’s assigned and spreadsheed doesn’t have the hostname in it already, then I want it to be inserted automaticaly. I have a code that returns ping time and it works fine, but I don’t know how to return hostname.

Function PingTime(strAddress) As Long
Dim objPing As Object, objStatus As Object

PingTime = “-1”
Set objPing = GetObject(“WinMgmts:{impersonationLevel=impersonate}”).ExecQuery _
(“SELECT * FROM Win32_PingStatus WHERE Address = ‘” & strAddress & “‘ “)
For Each objStatus In objPing
If Not IsNull(objStatus.StatusCode) And objStatus.StatusCode = 0 Then
PingTime = objStatus.Properties_(“ResponseTime”).Value
Exit For
End If
Next
Set objStatus = Nothing
Set objPing = Nothing
End Function


Solution: How do I return Hostname in excel cell by pinging IP address (VBA)

Use this function:

Public Function ResolveIP( _
ByVal Target As String, _
Optional ByVal Timeout As Long = 1000 _
) As String

Dim PingResult As Object
Dim PingStatus As Object

Set PingResult = GetObject(“WinMgmts:{impersonationLevel=impersonate}”).ExecQuery(“SELECT * FROM Win32_PingStatus WHERE Timeout = ” & Timeout & ” AND ResolveAddressNames = TRUE AND Address = ‘” & Target & “‘ “)
For Each PingStatus In PingResult
If Not IsNull(PingStatus.StatusCode) Then
If PingStatus.StatusCode = 0 Then
ResolveIP = PingStatus.Properties_(“ProtocolAddressResolved”).Value
Exit For
End If
End If
Next

End Function