I'm writing a macro in Microsoft Excel that makes an update in a table of my local SQL Server database,.
My connection string:
sConnect = "Driver={SQL Server};Data Source=(localdb)\MSSQLLocalDB;Database=Scrape;"
I get this error:
Data source name not found and no default driver specific
How do I write the connection string?
Ok, this should be pretty simple. See the link below.
https://www.erpsoftwareblog.com/2017/01/microsoft-excel-connections-sql-databases/
Also, check this out.
https://www.connectionstrings.com/sql-server/
Finally, to update a SQL Server table with Excel/VBA code, do the following.
Sub UpdateMyTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim rngName As Range
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=MyServer; " & _
"Initial Catalog=MyDB;" & _
"User ID=User;" & _
"Password=Pwd;" & _
"Trusted_Connection=No"
Set rngName = ActiveCell
cnn.Open cnnstr
uSQL = "UPDATE MyTable SET Field = 1 WHERE Field = ' " & rngName & " ' "
'Debug.Print (uSQL)
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
Post back, with specific details, if you have issues with this code. Thanks.
Related
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
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 having trouble converting/formatting a crosstab query SQL for VBA. I am getting a syntax error: expected something between the beginning of the request and the 'TRANSFORM' keyword.
I know that having the SQL start with the TRANSFORM command is most likely the issue, but after searching I have yet to find a solution.
I changed the "strSQl" to "strCrosstabQuery, but am still returning the same error.
Any assistance would be greatly appreciated.
See below for my current VBA.
Sub NewWorkRegional()
Sheets("Create Raw").Select
Range("A2:O" & Cells(Rows.Count, "A").End(xlUp).Row).Clear
strConn = "Provider=MSDASQL.1;Password=XXXXXXXX;Persist Security Info=True;User ID=KRATDAN;Data Source=DWPROD"
Set cn = New ADODB.Connection
cn.Open strConn
cn.CommandTimeout = 0
Dim strCrosstabQuery As String
strCrosstabQuery = "TRANSFORM Count(DNS_SBX_rpt_v_dm_all_work_orders.work_order_number) AS CountOfwork_order_number" & _
"SELECT DNS_SBX_rpt_v_dm_all_work_orders.sub_type_level_2" & _
"FROM DNS_SBX_rpt_v_dm_all_work_orders" & _
"WHERE (((DNS_SBX_rpt_v_dm_all_work_orders.reporting_region)='pacific') AND ((DNS_SBX_rpt_v_dm_all_work_orders.create_date) Between Date()-16 And Date()-3))" & _
"GROUP BY DNS_SBX_rpt_v_dm_all_work_orders.sub_type_level_2" & _
"PIVOT [create_date]+7-Weekday([create_date],7);"
'updated line above
Set rs = New ADODB.Recordset
rs.Open strCrosstabQuery, cn
Sheets("Results").Range("B92").CopyFromRecordset rs
End Sub
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.
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