VBA Error handling on ADODB Connection.Open - vba

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

Related

Microsoft access cant find file on path

Hello I keep getting an error message saying the path is wrong. I'm new at VBA Code and I just don't know how to solve it. This is what I wrote. I keep checking the path every time and copy-pasting the path and yet it can't find it. Sorry for my English - not main language.
Error message is:
Run time errror
Could not find file A:\Proccess_Assig1.accdb'.
The code is
Private Sub btn_buscar_Click()
Dim rs As New ADODB.Recordset
Dim conn As New ADODB.Connection
Dim strsql As String
strsql = "Select * from TBlClientes Where id= " & txtCliente.Value & ""
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=A:\Proccess_Asig1.accdb;persist security Info=False"
conn.Open
rs.Open strsql, conn
If rs.EOF Then
MsgBox "Id no existe"
txtCliente.Value = Nothing
txtNombre.Value = Nothing
txtApellido.Value = Nothing
txtTelefono.Value = Nothing
Else
txtCliente.Value = rs.Fields("Nombre")
txtApellido.Value = rs.Fields("ApellidoPaterno")
txtTelefono.Value = rs.Fields("Teléfono")
End If
rs.Close
conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
Check that you have the actual valid path A:\Proccess_Assig1.accdb doesn't seem like a standard path, try c:\Proccess_Assig1.accdb

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

How to update Sql table from excel directly?

I have an sql database and I am able to connect with excel spreadsheet. But when I update the table from excel directly it's not updating the database and once I click refresh all the entered data is no longer in the excel table
Is it possible to update sql database from excel without using any queries?
There are many ways to do this. I'd recommend something like this, to push data from Excel to SQL Server.
Sub ButtonClick()
'TRUSTED CONNECTION
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim strFirstName, strLastName As String
Dim server, username, password, table, database As String
With Sheets("Sheet1")
server = .TextBox1.Text
table = .TextBox4.Text
database = .TextBox5.Text
If con.State <> 1 Then
con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
'con.Open
End If
'this is the TRUSTED connection string
Set rs.ActiveConnection = con
'delete all records first if checkbox checked
If .CheckBox1 Then
con.Execute "delete from tbl_demo"
End If
'set first row with records to import
'you could also just loop thru a range if you want.
intImportRow = 10
Do Until .Cells(intImportRow, 1) = ""
strFirstName = .Cells(intImportRow, 1)
strLastName = .Cells(intImportRow, 2)
'insert row into database
con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
intImportRow = intImportRow + 1
Loop
MsgBox "Done importing", vbInformation
con.Close
Set con = Nothing
End With
Exit Sub
errH:
MsgBox Err.Description
End Sub
You can also try this, which uses a Where Clause.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Excel-PC\SQLEXPRESS"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=Excel-PC\SQLEXPRESS;DATABASE=Northwind;Trusted_Connection=Yes"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
Yes, you can directly via VBA or with other tools.
via VBA (via qry)
via SSIS (https://www.simple-talk.com/sql/ssis/moving-data-from-excel-to-sql-server-10-steps-to-follow/)
via managament studio (https://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/)
via MS ACCESS (with ODBC connection to server)
...

VBA in Access 2010 - Run-time Error 430

I’m getting a Run-time error '430': Class does not support Automation or does not support expected interface" on this line of code Set Me.lstResults.Recordset = rs or this Set Me![frmM_SearchForDocumentsSubForm].Form.Recordset = rs. I am trying to get the ADO Recordset based on a SQL stored procedure to appear in an unbound Listbox or Subform of an Access form. I’m on Win 7 Machine using Access 2010 connecting to SQL Server 2008:
On_Click event:
Private Sub cmdRun_Click()
'On Error Resume Next
Dim strSQL As String
'Stored procedure + parameters called from form
strSQL = "Exec sqlsp_searchalltables " & Me.txtTables & _
", " & "'%" & Me.txtSearchTerm & "%'"
OpenMyRecordset rs, strSQL
'debug - view procedure
Me.lblQuery.Caption = strSQL
Me.Repaint
Set Me.lstResults.Recordset = rs
'or this
'Set Me![frmM_SearchForDocumentsSubForm].Form.Recordset = rs
End Sub
I found some solutions for this error on the web and tried all of them to no avail. Most suggested checking the references which I did and verified.
I am able to successfully connect to the SQL server and have the results display in both a Listbox and Subform when I use DAO Querydef and a passthrough query or if I use this .listbox method:
With Me.lstResults
Do
strItem = rs.Fields("CLIENT_ID").Value
.AddItem strItem
rs.MoveNext
Loop Until rs.EOF
End With
I would prefer not to use the DAO method because I found I need the coding flexibility of ADO especially with connecting to multiple Recordsets in SQL. Thoughts?
FYI: My OpenMyRecordset public function in Module:
Option Compare Database
Option Explicit
Global con As New ADODB.Connection
Global rs As ADODB.Recordset
Global NoRecords As Boolean
Public Enum rrCursorType
rrOpenDynamic = adOpenDynamic
rrOpenForwardOnly = adOpenForwardOnly
rrOpenKeyset = adOpenKeyset
rrOpenStatic = adOpenStatic
End Enum
Public Enum rrLockType
rrLockOptimistic = adLockOptimistic
rrLockReadOnly = adLockReadOnly
End Enum
Public Function OpenMyRecordset(rs As ADODB.Recordset, strSQL As String, Optional rrCursor As rrCursorType, _
Optional rrLock As rrLockType, Optional bolClientSide As Boolean) As ADODB.Recordset
If con.STATE = adStateClosed Then
con.ConnectionString = "ODBC;Driver={SQL Server};Server=mysqlsvr;DSN=RecordsMgmt_SQLDB;UID=XXX;Trusted_Connection=Yes;DATABASE=RecordsManagementDB;"
con.Open
End If
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = con
.CursorLocation = adUseClient
.CursorType = IIf((rrCursor = 0), adOpenDynamic, rrCursor)
.LockType = IIf((rrLock = 0), adLockOptimistic, rrLock)
.Open strSQL
If .EOF And .BOF Then
NoRecords = True
Exit Function
End If
End With
End Function
You definitely do not have to do the looping method to just to populate the listbox. I'm not familiar with the OpenMyRecordset command you used, but I suspect that something in its functionality is what is causing this error (i.e., it's not opening the recordset in a manner compatible with the listbox). This is how I connected to a local instance of SQL Server Express and was able to populate a listbox.
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
With cn
.ConnectionString = _
"Provider=SQLOLEDB;Data Source=localhost\SQLEXPRESS;" & _
"Initial Catalog=Northwind;Trusted_Connection=yes"
.Open
End With
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = "SELECT FirstName, LastName FROM Employees"
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
Set Me.lstTest.Recordset = rs
Set rs = Nothing
Set cn = Nothing
You will have to make sure that you have the Microsoft ActiveX Data Objects Library reference enabled in your project.

DB2 connection from excel macro

I want to connect to DB2 from excel macro...This is my code, but it not working, Its giving error as 'Run-time Error'...Can anyone help me...
Option Explicit
Dim DBCONSRT, QRYSTR As String
Dim DBCON, DBRS As Object
Private Sub query()
DBCONSRT = "Driver=jdbc:db2://my_host;Database=PRTHD;hostname=NZ1;port=5355;protocol=TCPIP; uid=my_user;pwd=my_pass"
'CHANGE THE BELOW QUERY STRING ACCORDING TO YOUR NEED
QRYSTR = "select * from PRTHD.STRSK_OH_EOO"
Set DBCON = CreateObject("ADODB.Connection")
DBCON.ConnectionString = DBCONSRT
DBCON.Open
'BELOW CODE USED TO GET THE DATABASE CONECTION AND EXECUTE THE QUERY CHANGE ACCORDIGN TO YOUR NEED
Set DBRS = CreateObject("ADODB.Recordset")
With DBRS
.Source = QRYSTR
Set .ActiveConnection = DBCON
.Open
End With
End Sub
Edit: I have changed my code to the following, but I'm still getting an error. The Error is "cant create Object"..Can ayone help me..
Dim DBCONSRT, QRYSTR As String
Dim DBCON As Object
Sub query()
DBCONSRT = "Provider=MSDASQL.1;Persist Security Info=False;User ID=user;Data Source=NZ1;DSN=NZ1;UID=user;SDSN=;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=PRTHD;"
DBCON = CreateObject("OLEDB.Connection")
DBCON.ConnectionString = DBCONSRT
DBCON.Open()
End Sub
The JDBC functionality I am pretty sure is not supported through vba and I think you need to use ODBC connectors to connect to DB2 if you are trying to integrate it into excel.
Private Sub query()
DBCONSRT = "Provider=MSDASQL.1;Persist Security Info=False;User ID=user;Data Source=NZ1;DSN=NZ1;UID=user;SDSN=;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;In‌​itial Catalog=PRTHD;"
Using connection = New OleDbConnection(DBCONSRT )
connection.Open()
Dim cmd = connection.CreateCommand()
cmd.CommandText = QRYSTR //This is where your sql statement should go, or the variable that is equal to the query.
Using dr = cmd.ExecuteReader()
//Process your query results here
End Using
End Using
End Sub
Start with changing
DBCON = CreateObject("OLEDB.Connection")
to
Set DBCON = CreateObject("ADODB.Connection")
If you still get an error, double-check your connection string.