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
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
When I connect to Azure SQL database from MS Excel, I do not see the option to see stored procedures, I can see only tables and view for a chosen database. How do I execute a stored procedures to download results to excel?
Thanks for your time and help.
You can use Data-->Query to run the stored procedure in Azure SQL database from Excel.
Please follow my steps:
New Query-->From Azure-->From Azure SQL database:
SQL Server Database-->Advanced options-->Execute stored procedure statements:
Click OK--?choose Database to connect to Azure SQL-->See the result of stored procedure.
Then we can load the data into excel.
Note: I use Microsoft Office 2016 version.
I believe Azure Synapse is essentially the same as SQL Server, with a few minor differences. So, I'm not 100% sure that this will work, and I don't haccess to Azure now, but this will run a SPron sitting inside SQL Server.
Sub RunSProc()
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim strConn As String
Set cn = New ADODB.Connection
strConn = "Provider=SQLOLEDB;"
strConn = strConn & "Data Source=Your_Server_Name;"
strConn = strConn & "Initial Catalog=Your_Database_Name;"
strConn = strConn & "Integrated Security=SSPI;"
cn.Open strConn
Set cmd = New ADODB.Command
cmd.ActiveConnection = cn
cmd.CommandText = "MyOrders"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Refresh
cmd.Parameters(1).Value = ActiveSheet.Range("E1").Text
cmd.Parameters(2).Value = ActiveSheet.Range("E2").Text
Set rs = cmd.Execute()
If Not rs.EOF Then
Worksheets("sheet2").Range("A5:D500").CopyFromRecordset rs
rs.Close
End If
End Sub
If you want to make a request to SQL Server, and run any kind of SQL, you can do this.
Sub ADOExcelSQLServer()
' Carl SQL Server Connection
'
' FOR THIS CODE TO WORK
' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library
'
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 = "NORTHWND" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [Customers]" ' 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
' Dump to spreadsheet
For iCols = 0 To rs.Fields.Count - 1
Worksheets("Sheet1").Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
With Worksheets("sheet1").Range("a2:z500") ' Enter your sheet name and range here
'.ClearContents
.CopyFromRecordset rs
End With
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = 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