IPadress plaatsen in excel cel

Status
Niet open voor verdere reacties.

murdoch

Gebruiker
Lid geworden
7 dec 2005
Berichten
38
Ik ben op zoek naar een VBE/VBA stukje wat het IPadress ophaalt uit de pc.

Nu heb ik op internet wel voorbeelden zien staan, maar ik krijg deze niet werkend.

Ik zou graag in bv cel A1 het werkelijk IP Adres krijgen.
Daarnaast zou ik graag een check uitvoeren op de waarde die daar uit voorkomt.

Als de waarde in B1 (00:FF:AA:00:FF) gelijk is als in de waarde die uit het voorgaande script komt en die is gelijk mag de macro verder lopen.... en anders moet hij stoppen.

Wie kan me helpen.
 
murdoch,

Zet deze code in een module en roep een sub aan.
Pas hem naar je behoefte aan.
Code:
Option Explicit

Private Const IP_SUCCESS As Long = 0
Private Const WS_VERSION_REQD As Long = &H101
Private Const MIN_SOCKETS_REQD As Long = 1
Private Const SOCKET_ERROR As Long = -1
Private Const INADDR_NONE As Long = &HFFFFFFFF
Private Const MAX_WSADescription As Long = 256
Private Const MAX_WSASYSStatus As Long = 128
Private Type WSADATA
    wVersion As Integer
    wHighVersion As Integer
    szDescription(0 To MAX_WSADescription) As Byte
    szSystemStatus(0 To MAX_WSASYSStatus) As Byte
    wMaxSockets As Long
    wMaxUDPDG As Long
    dwVendorInfo As Long
End Type
Private Declare Function gethostbyname Lib "WSOCK32.DLL" _
                                       (ByVal hostname As String) As Long
Private Declare Sub CopyMemory Lib "kernel32" _
                               Alias "RtlMoveMemory" _
                               (xDest As Any, _
                                xSource As Any, _
                                ByVal nbytes As Long)
Private Declare Function WSAStartup Lib "WSOCK32.DLL" _
                                    (ByVal wVersionRequired As Long, _
                                     lpWSADATA As WSADATA) As Long
Private Declare Function WSACleanup Lib "WSOCK32.DLL" () As Long
Private Declare Function inet_addr Lib "WSOCK32.DLL" _
                                   (ByVal s As String) As Long
Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" _
                                         (ByVal Buffer As String, _
                                          Size As Long) As Long

Sub TestingFunction()
    If SocketsInitialize() Then
        MsgBox "IP address of " & GetPcName & " is " & GetIPFromHostName(GetPcName)
    End If
    SocketsCleanup
End Sub

Public Function GetIPFromHostName(ByVal sHostName As String) As String
'converts a host name to an IP address.
    Dim nbytes As Long
    Dim ptrHosent As Long  'address of hostent structure
    Dim ptrName As Long    'address of name pointer
    Dim ptrAddress As Long    'address of address pointer
    Dim ptrIPAddress As Long
    Dim sAddress As String
    sAddress = Space$(4)
    ptrHosent = gethostbyname(sHostName & vbNullChar)
    If ptrHosent <> 0 Then
        ptrName = ptrHosent
        ptrAddress = ptrHosent + 12
        'get the IP address
        CopyMemory ptrName, ByVal ptrName, 4
        CopyMemory ptrAddress, ByVal ptrAddress, 4
        CopyMemory ptrIPAddress, ByVal ptrAddress, 4
        CopyMemory ByVal sAddress, ByVal ptrIPAddress, 4
        GetIPFromHostName = IPToText(sAddress)
    End If
End Function

Private Function IPToText(ByVal IPAddress As String) As String
    IPToText = CStr(Asc(IPAddress)) & "." & _
               CStr(Asc(Mid$(IPAddress, 2, 1))) & "." & _
               CStr(Asc(Mid$(IPAddress, 3, 1))) & "." & _
               CStr(Asc(Mid$(IPAddress, 4, 1)))
End Function

Public Sub SocketsCleanup()
    If WSACleanup() <> 0 Then
        MsgBox "Windows Sockets error occurred in Cleanup.", vbExclamation
    End If
End Sub

Public Function SocketsInitialize() As Boolean
    Dim WSAD As WSADATA
    SocketsInitialize = WSAStartup(WS_VERSION_REQD, WSAD) = IP_SUCCESS
End Function

Public Function GetPcName() As String
    Dim strBuf As String * 16, strPcName As String, lngPc As Long
    lngPc = GetComputerName(strBuf, Len(strBuf))
    If lngPc <> 0 Then
        strPcName = Left(strBuf, InStr(strBuf, vbNullChar) - 1)
        GetPcName = strPcName
    Else
        GetPcName = vbNullString
    End If
End Function

Gevonden op Internet.
 
Leeg werkblad/menubalk/Data/externe gegevens/webquery/http://www.watismijnip.nl/

Zie bijlage
 

Bijlagen

Laatst bewerkt:
Perfect, beide oplossingen zijn een goede weg om verder te borduren :)

Eigenlijk wil ik ook nog een check op het macadress doen (vraag niet goed gesteld zie ik...:confused:)

In elk geval alvast bedankt voor de snelle oplossingen
 
De simpelste methode:

Code:
Sub IPMAC()
  Shell "winipcfg /all /batch E:\ipmac.txt", vbMinimizedNoFocus
   
  With ActiveSheet.QueryTables.Add("TEXT;E:\ipmac.txt", Range("A1"))
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierNone
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileOtherDelimiter = ":"
    .Refresh False
  End With
End Sub
 
De opdracht regel "winipcfg /all /batch E:\ipmac.txt" geeft een fout bij mij.
XP herkend het programma WINIPCFG niet....?

Met ""ipconfig /all >E:\ipmac.txt" zou het wel werken, alleen geeft hij een error op de Refresh regel.
Nu kijk ik maar hij maakt heb bestand blijkbaar niet aan?
 
Laatst bewerkt:
probeer het eens met

"ipconfig /all /batch E:\ipmac.txt"
 
Als ik kijk op http://vbnet.mvps.org/index.html?code/network/macaddress.htm staat er een code die een mac adress zou moeten toevoegen, echter ik krijg hem niet aan de gang....

Ik zal ongetwijfeld wat verkeerd doen. Kan iemand mij daarbij helpen?

Code:
Option Explicit

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2009 VBnet, Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Private Const NCBASTAT As Long = &H33
Private Const NCBNAMSZ As Long = 16
Private Const HEAP_ZERO_MEMORY As Long = &H8
Private Const HEAP_GENERATE_EXCEPTIONS As Long = &H4
Private Const NCBRESET As Long = &H32

Private Type NET_CONTROL_BLOCK  'NCB
   ncb_command    As Byte
   ncb_retcode    As Byte
   ncb_lsn        As Byte
   ncb_num        As Byte
   ncb_buffer     As Long
   ncb_length     As Integer
   ncb_callname   As String * NCBNAMSZ
   ncb_name       As String * NCBNAMSZ
   ncb_rto        As Byte
   ncb_sto        As Byte
   ncb_post       As Long
   ncb_lana_num   As Byte
   ncb_cmd_cplt   As Byte
   ncb_reserve(9) As Byte 'Reserved, must be 0
   ncb_event      As Long
End Type

Private Type ADAPTER_STATUS
   adapter_address(5) As Byte
   rev_major         As Byte
   reserved0         As Byte
   adapter_type      As Byte
   rev_minor         As Byte
   duration          As Integer
   frmr_recv         As Integer
   frmr_xmit         As Integer
   iframe_recv_err   As Integer
   xmit_aborts       As Integer
   xmit_success      As Long
   recv_success      As Long
   iframe_xmit_err   As Integer
   recv_buff_unavail As Integer
   t1_timeouts       As Integer
   ti_timeouts       As Integer
   Reserved1         As Long
   free_ncbs         As Integer
   max_cfg_ncbs      As Integer
   max_ncbs          As Integer
   xmit_buf_unavail  As Integer
   max_dgram_size    As Integer
   pending_sess      As Integer
   max_cfg_sess      As Integer
   max_sess          As Integer
   max_sess_pkt_size As Integer
   name_count        As Integer
End Type
   
Private Type NAME_BUFFER
   name        As String * NCBNAMSZ
   name_num    As Integer
   name_flags  As Integer
End Type

Private Type ASTAT
   adapt          As ADAPTER_STATUS
   NameBuff(30)   As NAME_BUFFER
End Type

Private Declare Function Netbios Lib "netapi32" _
   (pncb As NET_CONTROL_BLOCK) As Byte
     
Private Declare Sub CopyMemory Lib "kernel32" _
   Alias "RtlMoveMemory" _
  (hpvDest As Any, ByVal _
   hpvSource As Long, ByVal _
   cbCopy As Long)
     
Private Declare Function GetProcessHeap Lib "kernel32" () As Long

Private Declare Function HeapAlloc Lib "kernel32" _
  (ByVal hHeap As Long, _
   ByVal dwFlags As Long, _
   ByVal dwBytes As Long) As Long
     
Private Declare Function HeapFree Lib "kernel32" _
  (ByVal hHeap As Long, _
   ByVal dwFlags As Long, _
   lpMem As Any) As Long



Private Sub Command1_Click()

  'in calling, pass the character you
  'want as a delimiter between MAC
  'address members
   Text1.Text = GetMACAddress("-")
   
End Sub


Private Function GetMACAddress(sDelimiter As String) As String

  'retrieve the MAC Address for the network controller
  'installed, returning a formatted string
   
   Dim tmp As String
   Dim pASTAT As Long
   Dim NCB As NET_CONTROL_BLOCK
   Dim AST As ASTAT
   Dim cnt As Long

  'The IBM NetBIOS 3.0 specifications defines four basic
  'NetBIOS environments under the NCBRESET command. Win32
  'follows the OS/2 Dynamic Link Routine (DLR) environment.
  'This means that the first NCB issued by an application
  'must be a NCBRESET, with the exception of NCBENUM.
  'The Windows NT implementation differs from the IBM
  'NetBIOS 3.0 specifications in the NCB_CALLNAME field.
   NCB.ncb_command = NCBRESET
   Call Netbios(NCB)
   
  'To get the Media Access Control (MAC) address for an
  'ethernet adapter programmatically, use the Netbios()
  'NCBASTAT command and provide a "*" as the name in the
  'NCB.ncb_CallName field (in a 16-chr string).
   NCB.ncb_callname = "*               "
   NCB.ncb_command = NCBASTAT
   
  'For machines with multiple network adapters you need to
  'enumerate the LANA numbers and perform the NCBASTAT
  'command on each. Even when you have a single network
  'adapter, it is a good idea to enumerate valid LANA numbers
  'first and perform the NCBASTAT on one of the valid LANA
  'numbers. It is considered bad programming to hardcode the
  'LANA number to 0 (see the comments section below).
   NCB.ncb_lana_num = 0
   NCB.ncb_length = Len(AST)
   
   pASTAT = HeapAlloc(GetProcessHeap(), _
                      HEAP_GENERATE_EXCEPTIONS Or _
                      HEAP_ZERO_MEMORY, _
                      NCB.ncb_length)
            
   If pASTAT <> 0 Then
   
      NCB.ncb_buffer = pASTAT
      Call Netbios(NCB)
      
      CopyMemory AST, NCB.ncb_buffer, Len(AST)
              
     'convert the byte array to a string     
      GetMACAddress = MakeMacAddress(AST.adapt.adapter_address(), sDelimiter)
                          
      HeapFree GetProcessHeap(), 0, pASTAT

    Else
      Debug.Print "memory allocation failed!"
      Exit Function
   End If
   
End Function


Private Function MakeMacAddress(b() As Byte, sDelim As String) As String

   Dim cnt As Long
   Dim buff As String
   
   On Local Error GoTo MakeMac_error
 
  'so far, MAC addresses are
  'exactly 6 segments in size (0-5)
   If UBound(b) = 5 Then
   
     'concatenate the first five values
     'together and separate with the
     'delimiter char
      For cnt = 0 To 4
         buff = buff & Right$("00" & Hex(b(cnt)), 2) & sDelim
      Next
      
     'and append the last value
      buff = buff & Right$("00" & Hex(b(5)), 2)
         
   End If  'UBound(b)
   
   MakeMacAddress = buff
   
MakeMac_exit:
   Exit Function
   
MakeMac_error:
   MakeMacAddress = "(error building MAC address)"
   Resume MakeMac_exit
   
End Function
 
Het vreemde bij XP is dat je 2 stappen moet doen:

Shell "cmd"
Shell "ipconfig /all >E:\ipmac.text"

Als je dit met de hand doet, wordt het txt-bestand aangemaakt.
 
Ik ben nog even aan het knoeien gegaan. Alleen nu heb ik wel een mogelijkheid tot het verkrijgen van een mac adress, alleen ik heb 2 adapters.

Nu geeft hij op de eerste niets en op de 2de regel mijn macaddress.

Hoe kan ik ervoor zorgen dat deze adressen automatisch in een cel geplaatst worden zonder dat ik een druk knop hoef in te drukken?

Ik heb het voorbeeld met de code erbij gedaan.
 

Bijlagen

  • Macadress.xls
    Macadress.xls
    49,5 KB · Weergaven: 23
  • ScreenShot053.jpg
    ScreenShot053.jpg
    13,1 KB · Weergaven: 31
Macadress

Na wederom wat proberen heb ik het nu wel voor elkaar dat het macadress in rij A geplaatst wordt.. Het zal niet de beste methode zijn, maar het werkt nu wel.

Nu zou ik graag alleen nog willen dat het automatisch gebeurd ipv doormiddel van de drukknop in te drukken.

Kan iemand mij aangeven hoe ik dat moet doen?

Alvast bedankt
 

Bijlagen

De simpelste methode is:

Maak een batch-bestand met 1 opdrachtregel: ipconfig /all >E:\ipmac2009.txt

(Batch bestand:
  • Open leeg Word-document.
  • zet er de opdrachtregel in: ipconfig /all >E:\ipmac2009.txt
  • Menubalk/bestand/opslaan als/ bestandstype MSDOStekst
  • naam E:\ipmaclees.bat
  • sluit bestand

Inlezen in Excelbestand

Methode 1 integraal inlezen

Code:
Private Sub Workbook_open()
  shell "E:\ipmaclees.bat"
  With sheets(1).QueryTables.Add("TEXT;E:\ipmac2009.txt", Range("A1"))
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierNone
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileOtherDelimiter = ":"
    .Refresh False
  End With
End Sub

Methode 2 alleen Mac-adres inlezen in cel A3

Code:
Private Sub Workbook_open()
  shell "E:\ipmaclees.bat" 
  Open "E:\ipmac2009.txt" For input As #1
  Sheets(1).Range("A3") = Replace(Join(Filter(Split(Input(LOF(1), #1), vbCr), "Fysiek"), ""), Chr(9) & "Fysiek adres . . . . . . . . . : ", "")
  close #1
End Sub
 
Laatst bewerkt:
Methode 1

Deze werkt, alleen wil ik alleen het Macadress invoegen (ja ik ben lastig;))

Methode 2

Deze geeft wel een uitvoer op de E schijf met het juiste bestand.
Echter hij geeft aan dat hij het bestand niet kan vinden.
Dit heeft mogelijk te maken dat het bestand nog geschreven wordt op het moment dat hij hem probeert aan te spreken.

Als ik hem dan nogmaals uitvoer, en het bestand werkelijk bestaat, leest hij niets uit :confused: Nou dacht ik dat het zijn doordat ik 2 fysieke adressen heb, maar als ik 1 adapter uitschakel en het proces opnieuw herhaal werkt het nog niet?


Het punt is dat ik een soort van beveiliging wil toepassen, ik wil dus bij het openen een controle op het macadress laten uitvoeren waarna hij pas verder mag gaan met de verdere macro's.

Het moet dus eigenlijk een soort van security check worden. Vandaar dat ik ook voor een moeilijkere oplossing aan het zoeken ben, en hoop dat je met mijn eerdere post van vandaag iets kan...

Groeten
 
Opgelost

Ik had de code die ik eerder vandaag neer gezet had.. in een FORM staan ipv Module

Tja dan wordt het het zoeken. Maar het is opgelost. Een ieder bedankt voor zijn / haar support:thumb:
 
Laatste suggestie (Methode 2) aangepast.
 
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan