gpt4 book ai didi

vba - Word VBA 检索 IP 地址 "silently"

转载 作者:行者123 更新时间:2023-12-05 00:38:58 25 4
gpt4 key购买 nike

我需要将 IP 地址提取到 VBA 宏中。此代码有效,但命令对话框是短暂可见的,这看起来不太好。我可以使用修改来“默默地”吗?

Sub getIP()

Set objShell = CreateObject("WScript.Shell")
Set objExecObject = objShell.Exec("%comspec% /c ipconfig.exe")
Do Until objExecObject.StdOut.AtEndOfStream
strLine = objExecObject.StdOut.ReadLine()
strIP = InStr(strLine, "Address")
If strIP <> 0 Then
IPArray = Split(strLine, ":")
strIPAddress = IPArray(1)
End If
Loop
SynapseForm.LabelIP.Caption = strIPAddress

End Sub

更新 ,发现了一个使用 Wscript.Shell 写入临时文件的变体,这“静默”地工作,不如下面 Remou 的方法好
    Sub getIPAddress()

Dim IP_Address: IP_Address = GetIP()

If IP_Address = "0.0.0.0" Or IP_Address = "" Then
MsgBox "No IP Address found.", , ""
Else
MsgBox IP_Address
'MsgBox IP_Address, , "IP address"
End If

End Sub

Function GetIP()

Dim ws: Set ws = CreateObject("WScript.Shell")
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")

Dim TmpFile: TmpFile = fso.GetSpecialFolder(2) & "/ip.txt"
Dim ThisLine, IP

If ws.Environment("SYSTEM")("OS") = "" Then
ws.Run "winipcfg /batch " & TmpFile, 0, True
Else
ws.Run "%comspec% /c ipconfig > " & TmpFile, 0, True
End If

With fso.GetFile(TmpFile).OpenAsTextStream
Do While Not .AtEndOfStream
ThisLine = .ReadLine
If InStr(ThisLine, "Address") <> 0 Then
IP = Mid(ThisLine, InStr(ThisLine, ":") + 2)
End If
Loop
.Close
End With

'WinXP (NT? 2K?) leaves a carriage return at the end of line
If IP <> "" Then
If Asc(Right(IP, 1)) = 13 Then IP = Left(IP, Len(IP) - 1)
End If

GetIP = IP

fso.GetFile(TmpFile).Delete

Set fso = Nothing
Set ws = Nothing

End Function

最佳答案

我认为这可能更容易,它使用 WMI。

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
"SELECT * FROM Win32_NetworkAdapterConfiguration", , 48)
For Each objItem In colItems
If Not IsNull(objItem.IPAddress) Then
''Commented line
''Debug.Print "IPAddress: " & Join(objItem.IPAddress, ",")
''Message box
MsgBox "IPAddress: " & Join(objItem.IPAddress, ",")
''String for later use
strIPAddress = strIPAddress & Join(objItem.IPAddress, ",")
End If
Next
''Later
SynapseForm.LabelIP.Caption = strIPAddress

关于vba - Word VBA 检索 IP 地址 "silently",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4972532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com