LoginSignup
15
18

More than 5 years have passed since last update.

使用中のADユーザー名とコンピュータ名を簡単に取得

Last updated at Posted at 2015-09-03

単純に文字列として取得したいときはけっこうある。今まで後者を使ってきたけど、最近前者の方法を見つけた。

参考情報に挙げたページがけっこうおもしろかったので、2通り合わせてメモ(Office 2010で確認)

ADSystemInfo オブジェクトを参照

Private Sub Command1_Click()
'    On Error Resume Next
    Dim objSysInfo, objUser
    Set objSysInfo = CreateObject("ADSystemInfo")
    Set objUser = GetObject("LDAP://" & objSysInfo.UserName)
    Set objComp = GetObject("LDAP://" & objSysInfo.ComputerName)

    ' 取得内容:ADユーザー名,コンピュータ名
    ' 例:取得内容をメッセージボックスに表示
    MsgBox objUser.sAMAccountName & vbCrLf & objComp.cn

    Set objUser = Nothing
    Set objComp = Nothing
    Set objSysInfo = Nothing

End Sub

参考情報

"Nearly all men can stand adversity, but if you want to test a man's character, give him power" - Abraham Lincoln

  • Hey, Scripting Guy!: あなたはだれ
    • 易しい例から徐々に応用へ、通して読むとよく理解できる内容
    • もはや伝統的というか、文章序盤は(ほぼ必ず)ユーモアが入り、文中にも散りばめられている。日本語訳でもうまくユーモアが出ていると思う
    • 方法を早く知りたいときはやや面倒くさいけれども

Win32API を利用

' 標準モジュールに書く
Public Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Public Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
' 任意のSub(またはFunction)
Private Sub Command1_Click()
  Dim Name As String
  Dim Leng As Long
  Dim Ret As Long
  'バッファを確保
  Name=String(250,chr(0))
  Leng=Len(Name)

  Ret=GetUserName(Name,Leng)
  MsgBox "ユーザー名は" & Name & " です。"
  Ret=GetComputerName(Name,Leng)
  MsgBox "コンピュータ名は" & Name & " です。"
End Sub
' 他の例
' Excel VBA
Cells(1,1) = GetComputerName()
' Access VBA
Me.[ログオンユーザ名] = GetUserName()

参考情報

58.ユーザー名を取得する
59.コンピューター名を取得する

15
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
18