Getting computer name using VBA

与世无争的帅哥 提交于 2019-11-28 17:48:50
Dim sHostName As String

' Get Host Name / Get Computer Name

sHostName = Environ$("computername")

You can do like this:

Sub Get_Environmental_Variable()

Dim sHostName As String
Dim sUserName As String

' Get Host Name / Get Computer Name    
sHostName = Environ$("computername")

' Get Current User Name    
sUserName = Environ$("username")

End Sub

Looks like I'm late to the game, but this is a common question...

This is probably the code you want.

Please note that this code is in the public domain, from Usenet, MSDN, and the Excellerando blog.


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

You'll probably need this, too:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!