title: VBA Error handling on ADODB Connection.Open
body: <p>I have an ADODB connection in VBA for connecting to an SQLServer database. I want to catch the error that is raised when connection.Open is called and the given database is unreachable.</p>
  
  <p>My code looks like this:</p>
  
  <pre><code>Public Function Connect() As Boolean
  
  On Error GoTo DBError
  
      Dim dbServer As String
      Dim dbName As String
      Dim dbUser As String
      Dim dbPwd As String
  
      dbServer = DatabaseSettings.dbServer
      dbName = DatabaseSettings.dbName
      dbUser = DatabaseSettings.dbUser
      dbPwd = DatabaseSettings.dbPwd
  
      Dim connectionString As String
      connectionString = "Server=" &amp; dbServer &amp; ";Database=" &amp; dbName &amp; ";User Id=" &amp; dbUser &amp; ";Password=" &amp; dbPwd
  
      Set conn = New ADODB.Connection
      conn.Provider = "sqloledb"
      With conn
          .ConnectionTimeout = 2
          .CursorLocation = adUseClient
          .Open connectionString
          .CommandTimeout = 0
      End With
  
  Connect = True
  Exit Function
  
  DBError:
      Connect = False
  End Function
  </code></pre>
  
  <p>My problem is that when i try to run this code with an incorrect connectionString an error is raised and shown in a MsgBox and not caught by the "On Error GoTo DBError". </p>
  
  <p>Is there something wrong in my error handling code or do i need to find another way of catching this error? </p>
  
  <p>Thank you for your help. Any suggestions are welcome.</p>