VBA Form Connection Validation - sql

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:
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?

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

Related

Check the permission of user when calling `ADODB.connection.open`

I was stucked for many week on the following :
I need to delete and insert to SQL database using VBA Excel.
The code used to connect to database is :
sConnString= "string for the connexion to the database"
conn.Open sConnString, "username", "password"
Debug.Print conn.State
Here the answer is 1, which according to the Microsoft documentation, means that the connexion is opened.
Then I try to execute an SQL query, using the following code :
varSQL = "DELETE FROM mytable WHERE specificColumn = '" & specificVariable & "'"
Set Command1 = New ADODB.Command
With Command1
.ActiveConnection = conn
.CommandType = adCmdText
End With
With Command1
.CommandText = varSQL
.Execute NbRecordsAffected
End With
This returns access denied for the DELETE query
I want to know if the user with username has the permission to do the query, so I can be sure that the error comes form another thing
Thank you in advance
Consider capturing the more informative error via the ADO error collections using VBA error handling where you may receive if using an SQL Server database:
The DELETE permission was denied on the object 'mytable', database 'mydatabase' schema dbo
Sub Run_SQL()
On Error GoTo ErrorHandle
Dim conn As ADODB.Connection, Command1 AS ADODB.Command
'...your full code...
ExitHandle:
' RELEASE RESOURCES
Set Command1 = Nothing: Set conn = Nothing
Exit Sub
ErrorHandle:
' RAISE EVERY CONNECTION ERROR
Dim myError As ADODB.Error
For Each myError In conn.Errors
Msgbox myError.Number & " - " & myError.Description, "RUNTIME ERROR", vbCritical
Next myerror
Resume Exit_Handle
End Sub

VBA Connection String to Connect SQL server with SSL Certificate

I am using VBA connection string to connect SQL server in my VB script.It was running smoothly earlier.
Recently server team installed SSL certificate in that in which my macro is not running now and stating SSL Security error as like below snapshot.
Can anyone help me to fix the issue.
Thanks in advance!!!
Regards,
I would concatenate the values required for the connection string before you open it, instead of on cnSrc.Open.
I work with VBA and use ADO to query SQL server daily and I use the following format for my connection strings:
Provider=SQLOLEDB.1;User ID=UserName;Password=Password;Data Source=SeverName;Initial Catalog=DataBaseName
You can use the code below to test:
Private Sub TestConnection()
Dim cnSrc As ADODB.Connection
Dim CONNECTION_STRING As String
Dim cnServer As String, cndb As String, cnUser As String, cnPwd As String
cnServer = "SeverName"
cndb = "DataBaseName"
cnUser = "UserName"
cnPwd = "Password"
CONNECTION_STRING = "Provider=SQLOLEDB.1;User ID=" & cnUser & ";Password=" & cnPwd & ";" & _
"Data Source=" & cnServer & ";Initial Catalog=" & cndb
On Error GoTo CleanFail
Set cnSrc = New ADODB.Connection
cnSrc.Open CONNECTION_STRING
'bit wise comparison to check the connection's state
Debug.Assert (cnSrc.State And adStateOpen) = adStateOpen 'Debug.Assert pauses execution if false
CleanExit:
'close the connection
If Not cnSrc Is Nothing Then: If (cnSrc.State And adStateOpen) = adStateOpen Then cnSrc.Close
Set cnSrc = Nothing
Exit Sub
CleanFail:
Resume CleanExit
End Sub

Excel VB Database connection test

I have an excel spreadsheet with a bit of VB code that copies the data across to a access database. This copies the data from one sheet to a cache sheet and then from the cache sheet to the db using a flag to identify new data, This works ok but we would like to add a connection test to check if the connection to the database is ok.
This is the code i have below for the connection test:
Dim cnn As ADODB.Connection
Dim canConnect As Boolean
Set cnn = New ADODB.Connection
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=\\G-FILE1\Common_Files\All Users\Robert T\Cash Sheets\CashSheets.mdb;"
If cnn.State = adStateOpen Then
canConnect = True
cnn.Close
MsgBox "Connection UP", vbOKOnly
Else
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=\\G-FILE1\Common_File\All Users\Robert T\Cash Sheets\CashSheets.mdb;"
cnn.Close
If cnn.State = adStateClosed Then
canConnect = False
cnn.Close
MsgBox "Connection DOWN!", vbOKOnly
End If
End If
So what I want to do is this:
When button clicked > data is sent to cache sheet (Working) > Test DB connection > If not available, then msgbox user informing them > carry on caching sheet
I dont want the error window to appear, rather a msgbox and let the rest of the code carry on..
Hope this edit is a bit clearer..
Regards
It is enough if the file is available:
If Dir(accessFilePath) = "" Then
'file not found!
else
'file found!
end if

Code To eliminate need to enter password

I have an access form that pulls together data from different tables. Some of them require a username and password be entered. This is going out to other users and I would rather them not have to enter the information over and over. Is there a code that I can use that whenever it prompts for a password to have it automatically logged in?
Currently I already have a connection for one DB connection that runs whenever the DB is opened. It looks like:
Public Function StartUp()
Dim cnn As ADODB.Connection
Dim localrst As New ADODB.Recordset
Dim remoterst As New ADODB.Recordset
On Error Resume Next
Set cnn = New ADODB.Connection
cnn.Open "Provider=SQLOLEDB; Data Source=SOURCE; Initial Catalog=NAME;" _
& "User Id=ID; Password=PW;"
If cnn.State = adStateOpen Then
MsgBox ("You have an established connection with the L&TD SQL Server Database and the CDData table has been uploaded to the server.")
Else
MsgBox ("Cannot connect to SQL Server. Data will be stored locally to CDData Table until application is opened again with an established connection.")
End If
On Error GoTo 0
End Function
Is there a way to add more connections to this so it connects to all 3?
The literal answer is; no. You can't make a password form autofill. However, you can set up your connection string so that no one has to fill it in.
'Set up the connection string
strConn = "PROVIDER=SQLOLEDB;DATA SOURCE=MyServerName;INITIAL CATALOG=MyDatabaseName;UID=MyStandardUserID;PWD=MyStandardPassword;"
cnComments.Open strConn
You can also set it up without the username and password:
'Set up the connection string
strConn = "PROVIDER=SQLOLEDB;DATA SOURCE=MyServerName;INITIAL CATALOG=MyDatabaseName;TRUSTED_CONNECTION=yes;"
cnComments.Open strConn

VBA Error handling on ADODB Connection.Open

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.
My code looks like this:
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=" & dbServer & ";Database=" & dbName & ";User Id=" & dbUser & ";Password=" & 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
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".
Is there something wrong in my error handling code or do i need to find another way of catching this error?
Thank you for your help. Any suggestions are welcome.
Not sure if this is it, but in the VBE window make sure the Tools...Options...General...Error Trapping option is set to "Break on Unhandled Errors". If it were set to "Break on All Errors" this may bypass your handlers.
Try to use the below, worked here:
With conn
.ConnectionTimeout = 2
.CursorLocation = adUseClient
.ConnectionString = connectionString
.Open
.CommandTimeout = 0
End With