How to get my computer IP address with VBA

nector

Member
Local time
Today, 07:37
Joined
Jan 21, 2020
Messages
521
Hi all,

I'm trying to amend the code below to help me get the IP address from my computer IPV4 so that I do not need to worry about the dynamic changes of IP addresses each time I log in

The code below works for me, but it brings the unwanted extension instead of just only the IPaddress.

Code:
Function GetIPAddress()
    Const strComputer As String = "."   ' Computer name. Dot means local computer
    Dim objWMIService, IPConfigSet, IPConfig, IPAddress, i
    Dim strIPAddress As String

    ' Connect to the WMI service
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

    ' Get all TCP/IP-enabled network adapters
    Set IPConfigSet = objWMIService.ExecQuery _
        ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

    ' Get all IP addresses associated with these adapters
    For Each IPConfig In IPConfigSet
        IPAddress = IPConfig.IPAddress
        If Not IsNull(IPAddress) Then
            strIPAddress = strIPAddress & Join(IPAddress, ", ")
        End If
    Next

    GetIPAddress = strIPAddress
End Function


I will be running this code on an onload event

Me.txtIpaddress = GetIPAddress()

help me to cut off fe80:::d90:56f:dca8:5bb510.212.128.10

ipAddress.png
 
Use the Left() function in conjunction with InStr() to find the position of the first comma.
 
You can also query WMI without hassle :
Add a Reference to Microsoft Scripting Runtime
then run this:
Code:
Sub GetLocalIPAddress()
   
    Dim objWMIService As Object
    Dim Itms As Object
    Dim Itm As Object
    Dim IP As String

    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    Set Itms = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True")

    For Each Itm In Itms
        If Not IsNull(Itm.IPAddress) Then
            IP = Itm.IPAddress(0)
            Exit For
        End If
    Next Itm

    MsgBox "Local IP Address: " & IP
   
End Sub
 
You can also use the split method

Me.txtIpaddress =split( GetIPAddress(),”,”)(0)
 
Do you not need the external IP address?

We use a URL service that only returns the IPv4? Something like
SQL:
 HttpRequest.Open "GET", "https://api.ipify.org/", False
 
Last edited:

Users who are viewing this thread

Back
Top Bottom