VBA connecting to SQL Server Express database issue - sql-server

I installed a copy of SQL Server Express (latest). I am having trouble connecting to it.
Since I am the admin on this computer, it should be not needing user name password, because I created the database, and everything should fall under Windows authentication. My code is below.
I get an error:
Run-time error '-2147217843 (80040e4d)':
Invalid authorization specification
This error happens on attempting to open the connection.
When I launch a subform from main form, this code runs in initialize:
Option Explicit
Private objMyConn As ADODB.Connection
Private objMyRecordset As ADODB.Recordset
Private Sub UserForm_Initialize()
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Contact;"
objMyConn.Open
strSQL = "Select * from Contact where Lastname like " + Chr(39) + "%" + LastSearch + Chr(39) + " And Firstname like " + Chr(39) + "%" + FirstSearch + Chr(39)
MsgBox strSQL
End Sub

Add Integrated Security=SSPI to your connection string to indicate a trusted connection is desired:
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Contact;Integrated Security=SSPI"
EDIT
SQL Server Express installs a named instance by default so you may need to change the data source to include the instance name:
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;Initial Catalog=Contact;Integrated Security=SSPI"

use something like this instead of localhost
HP8300-0792\SQLEXPRESS
where HP8300-0792 is the name of your computer.

Related

Access Form : Bind a recordset from sql server

I try to use again a code who whas successful on the past to bind a recordset from sql server to an Access Form.
Dim serverAddress As String, DB As String, stADO As String
serverAddress = "xxx"
DB = "yyy"
stADO = "Provider=MSOLEDBSQL;Server=" & serverAddress & ";Database=" & DB & ";UID=admin;PWD=password;"
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
cn.ConnectionString = stADO
cn.Open
rs.CursorLocation = adUseClient
rs.Open "SELECT * FROM Table", cn, adOpenStatic, adLockReadOnly
DoCmd.OpenForm "Form_Name", acFormDS
'sanity check if we have data on the Recordset
Debug.Print rs(2)
Set Forms("Form_Name").Form.Recordset = rs
cn.Close
Set cn = Nothing
For sure the recorset is populate as debug.print rs(2) return a value.
When the command : "Set Forms("Form_Name").Form.Recordset = rs" is executed the database crashed and closed.
I have added also error management with on error goto but the DB crash without any message.
Thanks in advance for any help you could provide to resolve this issue.
Alexis
Error management without success
Use alternative connexion string
Test if the recordset is populated

Run Stored procedure in Azure SQL database from Excel and download results

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

Issues Connecting to Local SQL Server database

I have been trying to connect to a local SQL Server that I have created via Excel VBA but I am having issues.
I am able to connect to the database using the "Get Data" functionality within Excel and entering in the server as (Local DB)\MSSQLLocalDB.
However when I try connecting using VBA it does not work, using Windows authentication. Any ideas?
Here is the string I used:
strConnString = "Provider=SQLOLEDB;Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=SSPI"
The error I get is
Run-time error '2147467259 (80004005)'
[DBNETLIB][ConnectionOpen (Connect()).]
SQL Server does not exist or access denied.
This is how I use it, test it. TEST is Database name.
con.ConnectionString = "Provider=SQLOLEDB.1;" _
& "Server=(local);" _
& "Database=TEST;" _
& "Integrated Security=SSPI;" _
& "DataTypeCompatibility=80;"
Try it this way.
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

Not able to connect with database

I am new in Excel VBA. I have ready made code which is written for machine of IP address 199.63.106.70. Now i want same code to be run for another machine 199.56.122.155. I have install MS SQL server 2008 R2 on new machine. I also checked with connection using Data Connection Wizard. Data is Fetched.
But when i try to get data by click on button it display error message "Error in Process".
Controller is Jumping from oCon.Open
How can this error will be solved? is format of connection string is correct?
User Id and Password is windows login credentials which is used in string.
Dim oCon As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim rowcounter As Long
On Error GoTo errhandler
rowcounter = 2
Set oCon = New ADODB.Connection
oCon.connectionstring = "Driver={SQL Server};Server=199.63.106.70;Database=dashboard;User Id=dashboardadmin;Password=passwrd;"
oCon.Open
Set oRS = New ADODB.Recordset
oRS.ActiveConnection = oCon
oRS.Source = "SELECT HourlyReadingTimestamp, Hourlyreading,cost FROM MeterConsumptioNDetail where meterid=" & Range("J5").Value & " and HourlyreadingTimestamp between '" & Range("K5").Value & "' and '" & Range("L5").Value & " 23:59:59' order by HourlyreadingTimestamp"
oRS.Open
While Not oRS.EOF
Range("A" & rowcounter).Value = oRS.Fields(0).Value
Range("B" & rowcounter).Value = oRS.Fields(1).Value
Range("C" & rowcounter).Value = oRS.Fields(2).Value
rowcounter = rowcounter + 1
oRS.MoveNext
Wend
oCon.Close
If Not oRS Is Nothing Then Set oRS = Nothing
If Not oCon Is Nothing Then Set oCon = Nothing
MsgBox ("Data fetched successfully")
Exit Sub
errhandler:
MsgBox ("Error in process!")
End Sub
The connection string is incorrect if you want to use Integrated Security (Windows Login) use:
Driver={SQL Server};Server=199.63.106.70;Database=dashboard;Trusted_Connection=Yes;
The driver will deal with authentication based on the user running the process.

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

Resources