Home > database >  VBA Form Connection Validation
VBA Form Connection Validation

Time:11-11

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).

The issue that I'm encountering is if the user inserts a wrong login...then I get an error message and 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 but that doesn't work.

Could anyone advise how I could apply the If statement to check if the connection is valid?

CodePudding user response:

on error goto notgood
Cn.Open sConnect

<...>

notgood:
  MsgBox "Error connecting to Teradata"
  • Related