Active Directory Scripting – create User Account
Reference page: Active Directory – Sample Scripts (Excel/VBA)
How to create User Account
Description
User Account object could be created within its container object – Organizational Unit. The example below is based on the assumption that we successfully retrieved an instance of Organizational Unit.
Note. You need to login as an authorized person to successfully execute the script.
Common definitions
' Domain: DEV.ENV.COM Dim sDomain, dvDC sDomain = "DEV.ENV.COM" dvDC = Split(sDomain, ".") ' Organizational Units ' Company01 - Active Directory Path: "dev.env.com/Main/Client/Company01" ' User Accounts ' User02 - new user account; will be created in Company01 Dim sFirstname, sLastname, sLogin, sPassword sFirstname = "John" sLastname = "Doe" sLogin = "User02" sPassword = "abcd1234!"
How to create new User Account in Active Directory (Excel/VBA source code)
Note that we assume that we have a valid object instance in objOU.
If you build your own script
Depending on the scale of solution you implement you may want to refactor and expand the example presented below in order to exclude usage of global variables (sDomain, sFirstname, sLogin, etc.) and provide reporting functionality (based on sReturnMessage).
Public Function CreateUser(ByRef objOU)
Dim boolRC
Dim objUser
'
'Create User Account
On Error Resume Next
Set objUser = objOU.Create("User", "cn=" & sLogin)
boolRC = (Err.Number <> 0)
On Error GoTo 0
'Error-handling
If boolRC Then
sReturnMessage = "Failed to create User Account | LoginName = " & sLogin
CreateUser = False
Exit Function
End If
'Assign properties of User Account object
objUser.Put "sAMAccountName", sLogin
objUser.Put "userPrincipalName", sLogin & "@" & sDomain
'Submit
boolRC = SubmitInfo(objUser)
If Not boolRC Then
sReturnMessage = "Failed to create User Account (possibly, duplicate login or CN) | LoginName = " & sLogin
CreateUser = False
Exit Function
End If
'Set password
On Error Resume Next
objUser.SetPassword sPassword
boolRC = (Err.Number <> 0)
On Error GoTo 0
'Error-handling
If boolRC Then
sReturnMessage = "User Account creation uncomplete | Failed to set Password = " & sPassword
CreateUser = False
Exit Function
End If
'Assign firstname and lastname
objUser.Put "givenName", sFirstname
objUser.Put "sn", sLastname
objUser.Put "displayName", sFirstname & " " & sLastname
'Submit
boolRC = SubmitInfo(objUser)
If Not boolRC Then
sReturnMessage = "User Account creation uncomplete | Failed to set first/last name"
CreateUser = False
Exit Function
End If
CreateUser = True
End Function
'
'
'This function is used to submit data back to Active Directory and check if it's successfully accepted
Private Function SubmitInfo(ByRef objLDAPRecord)
Dim boolRC
On Error Resume Next
objLDAPRecord.SetInfo
boolRC = (Err.Number <> 0)
On Error GoTo 0
If boolRC Then
SubmitInfo = False
Else
SubmitInfo = True
End If
End Function

