SQL to VBA: Error importing table from SQL into excel - sql-server

In the code below, I keep getting an error message saying:
"Runtime Error '-2147467259 (80004005)': Automation Error Unspecified
Error"
The error pops up when I try and open the connection. All I want to do is import data from a local SQL DB into excel.
I don't know if it matters, but I am using SQL server 2014 express.
Sub connect()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim strConn As String
Dim connstr As String
Dim strSRV As String
Dim strDB As String
Dim sql_login As String
sqlquery = "SELECT top 10 * FROM [Source Contacts];"
connstr = "Driver={SQL Server native Client 11.0};Server=(LocalDB)\v11.0;AttachDBFileName=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SIT23DL_Validation.mdf;Database=SIT23DL_Validation;Trusted_Connection=Yes"
'Create the Connection and Recordset objects
Set conn = New ADODB.Connection
conn.ConnectionString = connstr
conn.Open
Set rs = conn.Execute(sqlquery)
If Not rs.EOF Then
'Transfer result
Sheets(1).Range("A1").CopyFromRecordset rs
'Close Recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
'Clean up
If CBool(conn.State And adStateopen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub

Agreed with the comments, most likely culprit is the connection string. Try connecting to your SQL instance using 'Microsoft SQL Server Management Studio' and attach the database through that interface (not through the connection string). If all that works, you can try the following (you may need to replace localhost with your actual machine name):
connstr = "Provider=SQLOLEDB;Data Source='localhost\v11.0';Initial Catalog='SIT23DL_Validation';Integrated Security=SSPI;Trusted_Connection=Yes"

Related

Connect to SQL Server in VBA if the server requires specific username and password?

I realized today that when you connect to SQL Server data source in Excel's native connection, it doesn't allow you to enter in a specific username and password. It just asks for server name and database.
In VBA , under the assumption that I wanted to import data from a SQL Server data query into Sheet1, can you please help me understand how to write that code?
For purposes of this exercise:
SQL Server Connection INFO
Server Name: TestingS,1633
Database Name: CarSales
username: car
password: sales
The query I want to run for simplicity sake can be: "select * from table"
I have been doing some research , but am getting a bit lost. I have no problem setting up standard queries with custom SQL via ODBC, but because I need VBA, it's very tricky for me. Please help.
This is an example of MSSQL.
Sub testMSSQL()
'Reference Microsoft ActiveX data object Library 2.8 ~~
Dim cnn As ADODB.Connection
Dim strSQL As String
Dim Ws As Worksheet
Set Ws = ActiveSheet
strSQL = "select * from table"
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" '<~~ mssql
' Open a connection using an ODBC DSN.
cnn.ConnectionString = "driver={SQL Server};" & _
"server=TestingS;uid=car;pwd=sales;database=CarSales"
Set rs = New ADODB.Recordset
rs.Open strSQL, cnn.ConnectionString, adOpenForwardOnly, adLockReadOnly, adCmdText
cnn.Open
If cnn.State = adStateOpen Then
Else
MsgBox "Not connected server"
Exit Sub
End If
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("a2").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

Execute SQL Query from excel

I'm a bit stuck for a while in a small project
to generate results from several
sql queries in several excel Sheets, I am trying to use SQL Server 2008 and it's the first time I code VBA
I tried this code (for a SQL single query) but I still have compilation problems
Sub New_Feuil1()
ThisWorkbook.Activate
'First clear the contents from the query
Worksheets("Feuil1").Select
Range("A2").Select
Do Until ActiveCell = ""
ActiveCell.Offset(1).Select
Loop
Range("A4", ActiveCell.Offset(-1, 3)).ClearContents
'Get reporting date
ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1")
'Format the value for use in the SQL query
ReportingDateFor = Format(ReportingDate, "yyyy-mm-dd")
Worksheets("Feuil1").Select
Range("A1").Select
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim StrQuery1 As String
Dim ConnectionString As String
ConnectionString ="ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=187.125.254.231;" & _
"Database=database;" & _
"UID=sa; PWD=pwd"
cnn.Open ConnectionString
cnn.CommandTimeout = 900
'Queries to be executed
StrQuery1 = StrQuery1 & "Select Id from Users"
rst.Open StrQuery1, cnn, adOpenForwardOnly, adLockReadOnly
rst.Close
Debug.Print "StrQuery1:"; StrQuery1
cnn.Close
ThisWorkbook.Sheets("Central Dashboard").Select
Sheets("Feuil1").Range("A2").CopyFromRecordset rst
End Sub
is there any other solution ?
it seems you are new to programming :).. before you use any variables please declare them this will help you to understand them quickly.
like:
Dim ReportingDate as Date
ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1")
Dim ReportingDateFor As String
ReportingDateFor = Format$(ReportingDate, "yyyy-mm-dd")
also check your connection string. try this connection string.
ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd"
Apart from that, looking at your code you are connecting to server, opening recordset, closing recordset and finally closing the connection AND THEN trying to retrieve the results. logically this will never work :) :)
try this:
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim cmd As ADODB.Command
Dim ConnectionString As String
ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd"
cnn.Open ConnectionString
'Queries to be executed
Dim StrQuery1 As String
StrQuery1 = StrQuery1 & "Select Id from Users"
'Prepare SQL execution
cmd.Name = "SelectUsers"
cmd.ActiveConnection = conn
cmd.CommandText = StrQuery1
Set rst = cmd.Execute
If Not rst.EOF Then
With Sheets(1).Cells ' Enter your sheet name and range here
.ClearContents ' clears the entire sheet
.CopyFromRecordset rst ' copy the result
End With
Else
MsgBox "no records found.."
End If
'After work done close connection
On Error Resume Next
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing

Excel VBA ODBC connection failed

I'm using Excel 2010 VBA to retrieve data from MS Access 2010 with ODBC connection to SQL Server R2 Express, in my previous machine there is no issue (32bit platform) but when I got new machine it's always said "ODBC connection to (odbc name) failed -2147467259".
From Access 2010 to SQL there is no issue, but when I retrieve data from Excel always trigger this error.
I have check the permission for the user (DBO), all the app in the same machine, all the services are on, ODBC setting is correct. During the execution of the script all OK except when the line is opening the table.
Function RetrieveProjectList()
Dim strConn As String
Dim conn As New ADODB.Connection
Dim rec As New ADODB.Recordset
Dim intColCount As Integer
Dim strName As String
Dim strSQL As String
On Error GoTo Error_Trap
strName = ThisWorkbook.path & "\DBSource V0.1.accdb"
Set conn = New ADODB.Connection
strConn = "Provider=microsoft.ACE.oledb.12.0;"
strConn = strConn & "Data Source=" & strName & ";"
conn.Open ConnectionString:=strConn
Set rec = New ADODB.Recordset
strSQL = "SELECT qryProjectList.* " & _
"FROM qryProjectList ORDER BY tblArea.AreaName,tblProject.ProjectName;"
rec.Open strSQL, conn, adOpenDynamic, adLockOptimistic
'Retrieve data from Access
rec.MoveFirst
If rec.Fields.count <> 0 Then
After syntax "rec.open ...." the error pop up.
In other machince are OK.
Question:
Is this related to OS version 64bit? What did I miss out here?
Any advice will be highly appreciated.
Thanks, seageath

Using SQL script through vb.net code

I am new to SQL Server. I often find scripts over internet to perform different functions with SQL Server but I donot know how to use them in vb.net.
For example I want to run the following code through my vb.net application, but donot know how to do so. Please advise
ALTER LOGIN sa ENABLE ;
GO
ALTER LOGIN sa WITH PASSWORD = '' ;
GO
Thanks
The following code might help. Its from http://www.daniweb.com/software-development/vbnet/code/216920
'Declare outside of class
Imports System.Data.SqlClient
'Declare inside of class >
Dim SQLStr As String
Private ConnString As String
'Connstring = Server Name, Database Name, Windows Authentication
connstring = "Data Source=myserver;Initial Catalog=databasename;Integrated Security=True"
'SQL Staments
'SQL query = myQuery = "SQL Statment"
SQLStr = "SELECT * FROM tblQuestion"
SQLStr = "INSERT into tblQuestion(Name, Question) VALUES('Fred', 'How to use SQL?')"
SQLStr = "UPDATE tblQuestion SET Answer = 'Like this' Where Question = 'How to use SQL?'"
SQLStr = "DELETE FROM tblQuestion WHERE Question='How to use SQL?'"
'Write to SQL
Dim SQLConn As New SqlConnection() 'The SQL Connection
Dim SQLCmd As New SqlCommand() 'The SQL Command
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStr 'Sets the SQL String
SQLCmd.ExecuteNonQuery() 'Executes SQL Commands Non-Querys only
SQLConn.Close() 'Close the connection
'Read from SQL
Dim SQLConn As New SqlConnection() 'The SQL Connection
Dim SQLCmd As New SqlCommand() 'The SQL Command
Dim SQLdr As SqlDataReader 'The Local Data Store
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStr 'Sets the SQL String
SQLdr = SQLCmd.ExecuteReader 'Gets Data
While dr.Read() 'While Data is Present
MsgBox(dr("Column Name")) 'Show data in a Message Box
End While
Loop While SQLdr.NextResult() 'Move to the Next Record
SQLdr.Close 'Close the SQLDataReader
SQLConn.Close() 'Close the connection

Running a simple VBA script to test a connection

I'm trying to test the connection of a GoDaddy SQL Server database. I'm getting an 'invalid connection string attribute.'
What's wrong with this script?
Dim cnn As ADODB.Connection
Dim canConnect As Boolean
Public Sub TestConnection()
Set cnn = New ADODB.Connection
cnn.Open "Provider=sqloledb;Data Source=GoDaddyServer.com;Initial Catalog=dBase1;UserID=userID; Password='password';"
If cnn.State = adStateOpen Then
canConnect = True
cnn.Close
End If
MsgBox canConnect
End Sub
IIRC, you have to specify the Provider property outside the connection string like so:
Dim conn
Set conn = New ADODB.Connection
conn.Provider = "sqloledb"
conn.Open "Data Source=GoDaddyServer.com; Initial Catalog=dbase1; User ID=userid; Password=pass;"
I have never seen a password quoted in a SQL Server connection string like you have. Try removing the quotes:
"Provider=sqloledb;Data Source=GoDaddyServer.com;Initial Catalog=dBase1;User ID=userID; Password=password;"
You might find connectionstrings.com useful in the future.
One can specify the provider direct within the connection string
Dim cnn as ADODB.Connection
Dim cnn_str as String
cnn_str = "Provider=SQLOLEDB;Data Source=SERVER;Initial Catalog=DB;User ID=sa;Password=PASSWORD"
Set cnn = New ADODB.Connection
cnn.Open cnn_str

Resources