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
Related
I can manually right click on SSMS and choose "Run as a different user" then input my windows authentication user and password which will successfully open the connection to my desired server and DBs.
Is there a way to invoke the "Run as a different User" option from Excel VBA and pass through the User and Password details?
The VBA code I currently have is as follows:
Public Sub SQL_Data()
Dim Conn As New ADODB.Connection
Dim SystemSever, Systemdb As String
Dim RS As ADODB.Recordset
Dim CMD As ADODB.Command
Dim SQL_1 As String
SystemServer = "ServerName"
Systemdb = "DBName"
Set Conn = New ADODB.Connection
Conn.CommandTimeout = 60000
Conn.ConnectionTimeout = 60000
Conn.Open "DRIVER={SQL Server};SERVER=" & SystemServer & ";DATABASE=" & Systemdb & ";Trusted_Connection=Yes;OPTION=16427"
Set RS = New ADODB.Recordset
Set CMD = New ADODB.Command
With CMD
.ActiveConnection = Conn
End With
With RS
.CursorLocation = adUseClient
End With
SQL_1 = "SELECT ....... " & _
"FROM .......... "
RS.Open SQL_1, Conn, adOpenStatic
If WorksheetFunction.CountA(Range("Table_Data")) > 1 Then Range("Table_Data").Delete
Range("Table_Data").CopyFromRecordset RS
RS.Close
Set CMD = Nothing
End Sub
The original question was presented in 2015. I was wanting to know if any one here is aware if a new vba code has been generated since then to string 1000+ rows?
I don't want to get into server and more complex issues if I don't have to.
See original post:
Importing more than 1000 rows from Excel to SQL-server
Your assistance is appreciated.
You should be able to find a solution here.
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Introduction
Or, consider this.
Sub Rectangle1_Click()
'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
Or........from Excel to SQL Server using 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
I am trying to connect sql with Access.
What I want to do is simply get data from mssql using select statement.
Here is the code.
Sub ConnectSQLServer()
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
Dim par As ADODB.Parameter
Dim strSQL As String
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn
Set cmd = New ADODB.Command
cmd.CommandText = "dbo.Version"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
strSQL = "SELECT * FROM dbo.Version"
cmd.Execute
conn.Close
Set conn = Nothing
Set cmd = Nothing
End Sub
When I execute this code, I get error like "[Microsoft][ODBC SQL Server Driver][SQL Server] The request for procedure 'Version' failed because 'Version' is a table object.'
I know that I need to add something after "strSQL = SELECT * FROM dbo.Version" but I do not know exactly how to fill in.
Could you please help me with this?
It looks like you are executing dbo.Version as a SP or a SQL Command which is wrong.
You should execute the command in strSQL object instead. So after the modifications your code will look something like this:
strSQL = "SELECT * FROM dbo.Version"
Set cmd = New ADODB.Command
cmd.CommandText = strSQL
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
EDIT 1
I replicated the same issue in MS Excel to read data from MS SQl Server by using the following code and it worked for me:
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=HARSH-SHARMA\SQLEXPRESS;Initial Catalog=db1;User ID=sa;Password=pass001;"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from Subject"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
Please try this.
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