title: Excel VBA - Getting a users LDAP string correct
body: <p>I don't know what's wrong with me, but I can't get this string right! I've got this Excel sheet of user information and I want to connect to AD via LDAP, but I get this automation error '-2147217900 (80040e14)', which probably means there's a syntax error in the LDAP string. Now, I use this function to pick up the users distinguished name. Then I return that and try to pass it through adoConnection.Execute.</p>
  
  <p>The returned LDAP string looks like this:</p>
  
  <pre><code>&lt;LDAP://CN=Bowie\,David,OU=Geniouses,OU=Music,DC=MasterDomain,DC=local&gt;;ADsPath;subtree
  </code></pre>
  
  <p>The code looks like this:</p>
  
  <pre><code>ldapStr = "&lt;LDAP://" &amp; getUsersDN("dbowie") &amp; "&gt;;ADsPath;subtree"
  </code></pre>
  
  <p>Function like this:</p>
  
  <pre><code>Public Function getUsersDN(ByVal strUsername As String)
  Const ADS_SCOPE_SUBTREE = 2
  
  Set objConnection = CreateObject("ADODB.Connection")
  Set objCommand = CreateObject("ADODB.Command")
  objConnection.Provider = "ADsDSOObject"
  objConnection.Open "Active Directory Provider"
  Set objCommand.ActiveConnection = objConnection
  
  objCommand.Properties("Page Size") = 1000
  objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
  
  objCommand.CommandText = _
      "SELECT distinguishedName FROM 'LDAP://dc=MasterDomain,dc=local' " &amp; _
          "WHERE objectCategory='user' " &amp; _
              "AND sAMAccountName='" &amp; strUsername &amp; "'"
  Set objRecordSet = objCommand.Execute
  
  objRecordSet.MoveFirst
  Do Until objRecordSet.EOF
      strDN = objRecordSet.Fields("distinguishedName").Value
      getUsersDN = strDN
      objRecordSet.MoveNext
  Loop
  End Function
  </code></pre>