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
Related
I opened a similar question before with no avail on:
'https://stackoverflow.com/questions/58408918/vba-runtime-error-when-connection-to-sql-database
but since a few things have been tried, I thought I'd try again.
The problem is with the "Open" command". I get a runtime error 80040e4d Error on login for the user 'XXXX'
I looked at a stack link with similar issue which unfortunately didn't help either:
VBA Runtime Error when connection to SQL Database
I also tried usind the connection wizard in Excel which worked, so my connection data is seemingly correct. I wanted to use the connection string used by excel for my code in my modul,but the main difference of the provider being "Microsoft.Mashup.OleDb.1" didn't really change anything.
Here is my code:
'''
Sub DBCOnnectII()
Dim cnConn As ADODB.Connection
Set cnConn = New ADODB.Connection
With cnConn
.Provider = "SQLOLEDB.1"
.CursorLocation = adUseClient
.ConnectionTimeout = 0
.Properties("Data Source").Value = "VMSQL19"
.Properties("Password").Value = "XXXX"
.Properties("User ID").Value = "XXXX"
.Properties("Initial Catalog").Value = "AuswertungenTest"
.Open
End With
End Sub
'''
Here try this more simplified approach. Make sure to add the correct reference to use the ADO libraries.
Private Sub NonRecordset()
Dim vbSql As String, cnnstr as String
Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
vbSql = vbSql & "SQL STATEMENT"
Debug.Print ; vbSql
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB;Data Source=YOURSERVER;Initial Catalog=YOURDATABASE;User ID=USERNAME;Password=PASSWORD; Trusted_Connection=No"
cnn.Open cnnstr
' cnn.Execute vbSql 'use this if just executing statement
' rs.Open vbSql, cnn 'use this if needing recordset
' if needing a recordset you'lll have to do something with said recordset:
' ThisWorkbook.Sheets("Sheet1").Range("A1").CopyFromRecordset rs
cnn.Close
Set cnn = Nothing
End Sub
I found out how complicated it is via this website, which gives all possible entries:
https://www.connectionstrings.com/ole-db-driver-for-sql-server/
For my purposes with ADO, and a trusted connection( windows authenticated) it was this one:
con.Open "Provider=MSOLEDBSQL;Server=vmsql19;Database=XXXX;Trusted_Connection=yes;"
Here is an example of Inert Into.
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=your_server_name"
'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
Here is an example of Select.
Sub ImportFromSQLServer()
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"
Database_Name = "your_db_name"
'User_ID = "******"
'Password = "****"
SQLStr = "select distinct ID from mytable1"
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & ";"
RS.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A1")
.ClearContents
.CopyFromRecordset RS
End With
RS.Close
Set RS = Nothing
Cn.Close
Set Cn = Nothing
End Sub
So I am quite new to VBA but I need to write a VBA macro which runs the stored procedure in Microsoft SQL server and then paste this data into the excel worksheet.
So far this is the code that I have, but I am not sure how to proceed? Is there sample code or a template for this particular procedure?
Sub Connection() ' create the connection
loginstatus = True
login.Show
Password = login.password_input
user = login.UserName
Dim con As ADODB.Connection
Dim stored_procedure As String
Dim ADODBCmd As ADODB.Command
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
'provide and create connection string
Dim connectionString As String
Dim location As String 'the server
location = "MyLocation"
connectionString = "Provider=SQLOLEDB; Network Library=DBMSSOCN;Data Source=" & location & ";Command Timeout=0;Connection Timeout=0;Packet Size=4096; Initial Catalog=ukmc; User ID=" & user & "; Password=" & Password & ";"
'handle when it is not possible to log in
On Error GoTo ConnectionError
con.Open connectionString
loginstatus = False
Exit Sub
'errorhandl0
ConnectionError:
MsgBox "Not possible to log in. Have you entered the correct password?"
'recordset - the data extracted
Set ADODBCmd = New ADODB.Command
End Sub
So i think I have created the connection, but how do I tell it which stored procedure to run and then how do i paste the data into a worksheet in my excel document?
From the link
myConnection.Open
Set myCommand.ActiveConnection = myConnection
Set myRecordSet.ActiveConnection = myConnection
myCommand.CommandText = strSQL
myCommand.CommandType = adCmdText
myCommand.Execute
myRecordSet.Open myCommand
'Paste to spreadsheet
ThisWorkbook.Worksheets("Report").Range("a2").CopyFromRecordset
myRecordSet
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"
I am using this syntax to run a SQL Server 2008 stored procedure from Excel 2013. Everything executes as it should on one PC, but if I attempt to run it on a second PC it errors out with an
OLEDB Connection error
Shouldn't since I am hardcoding the servername, username, and password the syntax run w/o a hitch on any PC?
Function RunSQLServerProc()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset
con.Open "Provider=SQLOLEDB;Data Source=Server;Initial Catalog=Database;User Id=userid;Password=password;Integrated Security=SSPI;Trusted_Connection=Yes;"
cmd.ActiveConnection = con
cmd.CommandText = "TestProc"
Set rs = cmd.Execute(, , adCmdStoredProc)
End Function
There are two ways to connect to SQL Server through VBA
1) Integrated Security=SSPI;
2) Provide a valid username & password through the VBA
When you use SSPI, the windows login credentials of the logged in user (i.e. of the Excel workbook) will be used.
Now for you, since you are not wanting to use windows credentials you need to provide a SQL server logon with the User ID and password you specify, and that must also be associated with an account in the database with the privileges that you need.
These two samples work perfectly fine for me.
Option Explicit
Sub CallSprocOne()
Dim con As Connection
Dim rst As Recordset
Dim strConn As String
Set con = New Connection
strConn = "Provider=SQLOLEDB;"
strConn = strConn & "Data Source=LAPTOP\SQL_EXPRESS;"
strConn = strConn & "Initial Catalog=Northwind;"
strConn = strConn & "Integrated Security=SSPI;"
con.Open strConn
'Put a country name in Cell E1
Set rst = con.Execute("Exec dbo.TestNewProc '" & ActiveSheet.Range("E1").Text & "'")
'The total count of records is returned to Cell A5
ActiveSheet.Range("A5").CopyFromRecordset rst
rst.Close
con.Close
End Sub
Sub CallSprocTwo()
Dim con As Connection
Dim rst As Recordset
Set con = New Connection
con.Open "Provider=SQLOLEDB;Data Source=LAPTOP\SQL_EXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;"
Set rst = con.Execute("Exec dbo.[Ten Most Expensive Products]")
'Results of SProc are returned to Cell A1
ActiveSheet.Range("A1").CopyFromRecordset rst
rst.Close
con.Close
End Sub
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