Search code examples
sqlexcelvbateradataadodb

Form Connection Validation


I have a VBA form that opens upon opening Excel which requires user login credentials and checks if it connects to the teradata database.

Private Sub cmdLogin_Click()    
    Dim Cn As ADODB.Connection
    Dim Rc As ADODB.Recordset
    Set Cn = New ADODB.Connection
    Dim user As String
    Dim password As String
    Dim sConnect As String
      
    user = Me.txtUserID.Value
    password = Me.txtPassword.Value
    
    sConnect = "Driver={Teradata};DBCname=TDPREP01;DatabaseName=DBADMIN ;Uid=" & user & ";Pwd=" & password & "; Authentication=LDAP;"
    
    Cn.Open sConnect
    
    If Cn.State = 1 Then        
        Unload Me
        Application.Visible = True
        Worksheets("do not open!").Cells(1, 1) = user
        Worksheets("do not open!").Cells(2, 1) = password            
    Else
        MsgBox "Invalid login credentials. Please Try again.", vbOKOnly + vbCritical, "Invalid Login Details"
    End If
End Sub

If details are correct then I store the login details (to use later one for other modules).

If the user inserts a wrong login my app crashes with the following error:
enter image description here

Obviously this is due to the app crashing upon the Cn.Open sConnect

Is there a way to check if the connection is valid with an if statement?

I tried something like If Cn.Open sConnect = True Then.

How I could apply the If statement to check if the connection is valid?


Solution

  • on error goto notgood
    Cn.Open sConnect
    
    <...>
    
    notgood:
      MsgBox "Error connecting to Teradata"