Setting a connection to an access database in VBA crashes excel - vba

This is the code I use to open a connection to an access database from excel. It used to work for more than a year.
Set dbname = New ADODB.Connection
theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open theconnection
End With
By trial an error I've come to the conclusion that this line is causing the problem.
Set dbname= New ADODB.Connection
The problem began after an automatic update of my PC
My Excel version 2016 MSO (16.0.7726.1036) 32-bit
Please let me know if you have run also into this problem, and if you know any fix or workaround.

try to uncheck your 'ActiveX Data Objects' references and add them back:
Tools - References
or
use object to define a database:
Dim dbname As Object
Set dbname = CreateObject("ADODB.Connection")
or
if you create connection variable like this:
Dim con as New ADODB.Connection
change it to:
Dim con as ADODB.Connection
Set con = New ADODB.Connection

Maybe
Dim dbname As Object
Set dbname = CreateObject("ADODB.Connection")
theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open theconnection
End With
I used like this , all code
Dim Rs As Object
Dim strConn As String
Dim i As Integer
Dim strSQL As String
strSQL = "select * from [table] "
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 12.0;"
Set Rs = CreateObject("ADODB.Recordset")
Rs.Open strSQL, strConn
If Not Rs.EOF Then
With Ws
.Range("a1").CurrentRegion.ClearContents
For i = 0 To Rs.Fields.Count - 1
.Cells(1, i + 1).Value = Rs.Fields(i).Name
Next
.Range("a" & 2).CopyFromRecordset Rs
End With
End If
Rs.Close
Set Rs = Nothing

Related

VBA connect with ADO to SQL Server (Windows authenticated)

I get a runtime error 3709 when trying to connect via VBA to a SQL Server using Windows authentication.
The problem occurs on this line:
.ActiveConnection = conn
Here is the complete code used to connect:
Dim strConn As String
Dim wsReport As Worksheet
Dim col As Integer
strConn = "Provider=SQLOLEDB;"
strConn = strConn & "Server=" & Server_Name & ";"
strConn = strConn & "Database=" & Database_Name & ";"
strConn = strConn & "Trusted_Connection=yes;"
strConn = strConn & "Integrated Security=True;"
Set conn = New ADODB.Connection
With conn
.ConnectionString = strConn
.CursorLocation = adUseClient
End With
Set rst = New ADODB.Recordset
With rst
.ActiveConnection = conn
.Open Source:=SQL_Statement
End With
Set wsReport = ThisWorkbook.Worksheets.Add
With wsReport
For col = 0 To rst.Fields.Count - 1
.Cells(1, col + 1) = rst.Fields(col).Name
Next col
End With
Or is ADO out of date now?
the solution was "Provider=MSOLEDBSQL;Server=XX;Database=XXXX;Trusted_Connection=yes;"
THis website gives all the different combinations according to the exact case, showing the complexities of connections with SQL-Server:
https://www.connectionstrings.com/ole-db-driver-for-sql-server/

SQL Query Returns empty Recordset

I'm trying to learn how to connect to a SQL Server DB from Excel DB. I've tried to reduce the code to dead simple to begin with. I've looked at several answers to related questions, however, I cannot figure out why this doesn't work. It executes all the way through. (The code shown here is somewhat anonymized.)
The query finds the database, because if the table name is invalid it throws an error. However it always returns record count = -1. I can eyeball the table in MSSMS and it has data. Same result for other tables in the DB.
Public Sub ADOtest1()
Dim Conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConnString As String
strConnString = "Provider='SQLOLEDB'" & ";" & _
"Data Source='XXX-XPS\SQLEXPRESS'" & ";" & _
"Initial Catalog='XXXXX'" & ";" & _
"Integrated Security='SSPI'"
Set Conn = New ADODB.Connection
Conn.Open strConnString
' the query finds the DB, because if the table name is incorrect, it throws an error
strSQLString = "SELECT * from t300_XXXX"
Set rs = Conn.Execute(strSQLString)
wrkRecordCount = rs.RecordCount
'--- just some test breakpoints
If wrkRecordCount = -1 Then
a = "" '--- code keeps arriving here
Else
a = ""
End If
rs.Close
Conn.Close
End Sub
Answer from Srinika below worked:
Set rs = Conn.Execute(strSQLString)
rs.Close
rs.CursorLocation = adUseClient
rs.Open
I'll post two examples, so please refer.
First Example
Sub ExampleSQL()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strSQL As String
Set cnn = New ADODB.Connection
'Set the provider property to the OLE DB Provider for ODBC.
'cnn.Provider = "MSDASQL"
'cnn.Provider = "Microsoft.ACE.OLEDB.12.0"
'cnn.Provider = "MSOLAP"
'cnn.Provider = "SQLOLEDB.1"
' Open a connection using an ODBC DSN.
cnn.ConnectionString = "driver={SQL Server};" & _
"server=severname;uid=sa;pwd=password;database=test"
Set rs = New ADODB.Recordset
strSQL = "SELECT * FROM [your Table] "
rs.Open strSQL, cnn.ConnectionString, adOpenForwardOnly, adLockReadOnly, adCmdText
cnn.Open
If cnn.State = adStateOpen Then
Else
MsgBox "Sever is not connected!! "
Exit Sub
End If
If Not rs.EOF Then
With Ws
.Range("a4").CurrentRegion.ClearContents
For i = 0 To rs.Fields.Count - 1
.Cells(4, i + 1).Value = rs.Fields(i).Name
Next
.Range("a5").CopyFromRecordset rs
.Columns.AutoFit
End With
Else
MsgBox "No Data!!", vbCritical
End If
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
End Sub
Second Example
Sub getDataFromServer()
Dim con As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim i As Integer
con.ConnectionString = "Provider=SQLOLEDB.1;" _
& "Server=(local);" _
& "Database=TEST;" _
& "Integrated Security=SSPI;" _
& "DataTypeCompatibility=80;"
con.Open
Set cmd.ActiveConnection = con
cmd.CommandText = "SELECT * FROM [your Table]"
Set rs = cmd.Execute
Range("A1").CopyFromRecordset rs
con.Close
Set con = Nothing
End Sub

If InputBox equals Value1 then connect to Database1

I'm trying to create a VBA code that would connect to a specific database based on the user's input. E.g. if a user enters DB1 into the prompt, the code will run the following query: SELECT * FROM MyServerName.DB1.dbo.Table
Here is what I've got so far:
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim strSQL As String
Dim DB As Variant
DB = InputBox("Please enter the Database Name.")
sConnString = "Provider=SQLOLEDB;Data Source=MyServerName;" & _
"Integrated Security=SSPI;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Unsuccessful attempt to use the Else/If statement:
if '" & DB & "' = "DB1" then
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM MyServerName.DB1.dbo.Table ;")
elseif '" & DB & "' = "DB2" then
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM MyServerName.DB2.dbo.Table ;")
else
MsgBox "No records returned. Enter the correct Database Name.", vbCritical
End If
If Not rs.EOF Then
Sheets("Sheet1").Range("A2").CopyFromRecordset rs
rs.Close
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
The connection itself is working just fine when I use the select statement without Else/If. Does anyone know how to fix this? Thanks so much!
You could just use the DB variable to decide which database to use
Set rs = conn.Execute("SELECT * FROM [MyServerName].[" & DB & "].dbo.table ;")

Insert Data to Excel from SQL Table using a Stored Procedure

I would like to insert data from a SQL Table to an Excel sheet everyday using a stored procedure. It has to delete the data in excel and insert the new data to same sheet.
How do I do this?
I get an error in this code
Sub Connecion()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=(10.200.157.110);INITIAL CATALOG=Brickstream_DEVMGR;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
End Sub
Below code worked for me
Sub GetDataFromADO()
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=10.200.157.110;Initial Catalog=Brickstream_DEVMGR;User ID=usr_bayi;Password=3Ay1usr;"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from DEALER_DETAILED"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A2").CopyFromRecordset (objMyRecordset)
End Sub
Easy ask.
Sub ADOExcelSQLServer()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "your_server_name" ' Enter your server name here
Database_Name = "Northwind" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM Orders" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A2:Z500")
.ClearContents
.CopyFromRecordset rs
End With
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub

Copying ADO recordset into excel worksheet

I'm trying to open a CSV file and query it and return the results into column A of the second worksheet of "ThisWorkbook".
I'm not getting any errors so I do not see why it is not copying the record set into excel.
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim currentDataFilePath As String
Dim currentDataFileName As String
Dim nextRow As Integer
currentDataFilePath = "C:\Users\M\folder\"
currentDataFileName = "csv-file"
con.Open "Provider=Microsoft.JET.OLEDB.4.0;" & _
"Data Source=" & currentDataFilePath & ";" & _
"Extended Properties=""text;HDR=NO;FMT=Delimited;IMEX=1"""
'rs.ActiveConnection = con
rs.Open "SELECT Name FROM [" & currentDataFileName & ".csv] WHERE Datatype ='TYPE3'",
con
ThisWorkbook.Worksheets("Sheet2").Range("A:A").CopyFromRecordset rs
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
End Sub
You might refer to the CopyFromRecordset() method.
Based on your code above, after the rs.Open command you would add something like this:
ActiveWorksheet.Range("A1").CopyFromRecordset rs
See more here: http://msdn.microsoft.com/en-us/library/office/ff839240%28v=office.15%29.aspx