Existe-t-il un moyen d'obtenir le nom de l'ordinateur en VBA ?
Réponses
Trop de publicités?
Sarfraz
Points
168484
Nile
Points
903
On dirait que je suis en retard pour le jeu, mais c'est une question courante...
C'est probablement le code que vous voulez.
Veuillez noter que ce code est dans le domaine public, provenant de Usenet, MSDN et du blog Excellerando .
Public Function ComputerName() As String
'' Returns the host name
'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:
' Dim objNetwork As IWshRuntimeLibrary.WshNetwork
' Set objNetwork = New IWshRuntimeLibrary.WshNetwork
Dim objNetwork As Object
Set objNetwork = CreateObject("WScript.Network")
ComputerName = objNetwork.ComputerName
Set objNetwork = Nothing
End Function
Vous aurez probablement aussi besoin de ceci :
Public Function UserName(Optional WithDomain As Boolean = False) As String
'' Returns the user's network name
'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:
' Dim objNetwork As IWshRuntimeLibrary.WshNetwork
' Set objNetwork = New IWshRuntimeLibrary.WshNetwork
Dim objNetwork As Object
Set objNetwork = CreateObject("WScript.Network")
If WithDomain Then
UserName = objNetwork.UserDomain & "\" & objNetwork.UserName
Else
UserName = objNetwork.UserName
End If
Set objNetwork = Nothing
End Function
QHarr
Points
24420
Une méthode shell pour lire la variable d'environnement pour cette courtoisie de devhut
Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")
La même source donne une méthode API :
Option Explicit
#If VBA7 And Win64 Then
'x64 Declarations
Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
'x32 Declaration
Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If
Public Sub test()
Debug.Print ComputerName
End Sub
Public Function ComputerName() As String
Dim sBuff As String * 255
Dim lBuffLen As Long
Dim lResult As Long
lBuffLen = 255
lResult = GetComputerName(sBuff, lBuffLen)
If lBuffLen > 0 Then
ComputerName = Left(sBuff, lBuffLen)
End If
End Function