Cannot connect to sql server with VBA (Run-time error (80040e14)) - sql-server

I am trying to connect to my Sql database and get one simple recordset out of it running this code:
Sub ConnectToSQL()
Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
With cnn
.ConnectionString = "File Name=C:\inetpub\tc\TEST.udl"
.Open
End With
With cmd
.ActiveConnection = cnn
.CommandType = xlCmdSql
.CommandText = "SELECT * FROM TEST"
End With
rs.Open cmd.Execute, cnn
If Not rs.EOF Then
Sheets(1).Range("A1").CopyFromRecordset rs
rs.Close
Else
MsgBox "No records returned", vbCritical
End If
cn.Close
Set cn = Nothing
Set rs = Nothing
End Sub
As a result I get the run-time error message (80040e14) What could be wrong here?
Thanks,

Do you want to try following? Please do not forget to add Tools> Refernces if necessary.
Sub ConnectToSQL()
Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim ConnectionString As String
Set cnn = New ADODB.Connection
ConnectionString = "File Name=C:\inetpub\tc\TEST.udl"
cnn.Open ConnectionString
cnn.CommandTimeout = 900
strquery = "SELECT * FROM TEST;"
'MsgBox strquery
rs.Open strquery, cnn
If Not rs.EOF Then
Sheets(1).Range("A1").CopyFromRecordset rs
rs.Close
Else
MsgBox "No records returned", vbCritical
End If
cnn.Close
Set cnn = Nothing
Set rs = Nothing
End Sub

Related

VBA connecting to SQL Server

I am having trouble when connecting VBA to SQL Server:
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
rs.Open = "SELECT * FROM [dbo].[Version]"
cmd.Execute rs
Set conn = Nothing
Set cmd = Nothing
sConnString = ""
End Sub
I just want to select all values from the table named [dbo].[Version], but when I execute it, I get an error:
Compile error: Expected Function or Variable'
and the line with rs.Open is highlighted.
Would you help me to solve this problem?
Open is a method, and cannot be set with an =.
You probably want something like this:
rs.Open "SELECT * FROM [dbo].[Version]", conn
Once you have called Open, then you can iterate through the Recordset's rows using the EOF property and the MoveNext method:
Do While Not rs.EOF
Debug.Print rs.Fields(1)
'You could also use rs!FieldName, where FieldName is the name of a column
Loop
Change your code to the following:
Set cmd = New ADODB.Command
cmd.CommandText = "SELECT * FROM [dbo].[Version]"
cmd.CommandType = adCmdText
cmd.ActiveConnection = conn
Set rs = cmd.Execute
Do While Not rs.EOF
'do something with rs.Fields(0) '
rs.MoveNext
Loop
Set conn = Nothing
Set cmd = Nothing
rs.Fields is a zero based collection that means that the first field is 0, not 1.
You can get subsequent fields by rs.Fields(1), rs.Fields(2) etc. Or you can use Field names, with the syntax rs.Fields("MyFieldName").
Note when using a string command ("SELECT * FROM ..") the CommandType is adCmdText. The syntax for the Recordset is SET rs = cmd.Execute. Also you must invoke MoveNext in your loop, otherwise you get stuck in the loop!

I need to export sql server results to new excel work book?

I need results into a new workbook, at present am getting the results in existing workbook?
Sub ConnectSqlServer()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Workbooks.Add
ActiveWorkbook.SaveAs "C:\WorkbookName.xls"
sConnString = "Provider=SQLOLEDB;Data Source=PRATEEP-PC\SQLEXPRESS;" & _
"Initial Catalog=PPDS_20Dec_V1_Decomposition;" & _
"Integrated Security=SSPI;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
rsstring = "SELECT * FROM GE_PRODUCT_RESOURCE_MASTER;"
rs.Open rsstring, sConnString
ActiveSheet.Range("B3").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
Tried it and it worked fine. Anyway to make it bulletproof.
Sub ConnectSqlServer()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Set NewWorkbook = Workbooks.Add 'To avoid ActiveWorkbook
sConnString = "Provider=SQLOLEDB;Data Source=PRATEEP-PC\SQLEXPRESS;" & _
"Initial Catalog=PPDS_20Dec_V1_Decomposition;" & _
"Integrated Security=SSPI;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
rsstring = "SELECT * FROM GE_PRODUCT_RESOURCE_MASTER;"
rs.Open rsstring, sConnString
NewWorkbook.Range("B3").CopyFromRecordset rs 'directly call the NewWorkbook
rs.Close
conn.Close
NewWorkbook.SaveAs "C:\WorkbookName.xls" 'Save after your change
End Sub

I need to insert data into SQL server from Excel using VBA

I need to insert test-vba.xlsx data into SQL server to the particular database
Sub insertion()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim m, nrows As Integer
Set wkb = Workbooks("test-vba.xlsx").Worksheets("Sheet1").Activate
sConnString = "Provider=SQLOLEDB;Data Source=PRATEEP-PC\SQLEXPRESS;" & _
"Initial Catalog=PPDS_07Dec_V1_Decomposition;" & _
"Integrated Security=SSPI;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
For m = 0 To nrows - 1
Here are a couple ideas.
Sub UpdateTable()
Dim cnn As Object
Dim wbkOpen As Workbook
Dim objfl As Variant
Dim rngName As Range
Workbooks.Open "C:\Users\Excel\Desktop\Excel_to_SQL_Server.xls"
Set wbkOpen = ActiveWorkbook
Sheets("Sheet1").Select
Set rngName = Range(Range("A1"), Range("A1").End(xlToLeft).End(xlDown))
rngName.Name = "TempRange"
strFileName = wbkOpen.FullName
Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes"";"
nSQL = "INSERT INTO [odbc;Driver={SQL Server};Server=Server_Name;Database=[Database_Name].[dbo].[TBL]]"
nJOIN = " SELECT * from [TempRange]"
cnn.Execute nSQL & nJOIN
MsgBox "Uploaded Successfully"
wbkOpen.Close
Set wbkOpen = Nothing
End Sub
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 = "Server_Name;Database=Database_Name;Trusted_Connection=True;"
'Create a new Command object
Set cmd = New adodb.Command
'Open the connection
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-13 WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Open the Connection to the database
cnn.Open
'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 another idea.
Sub Button_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
Also, check out the links below.
http://www.cnblogs.com/anorthwolf/archive/2012/04/25/2470250.html
http://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm

VBA SQL Server Select

I was wondering if you could please check my code in VBA (Excel) to retrieve data from a SQL Server database, and insert it in the sheet.
It returns an error according the picture attached.
Sub ConnectionTest()
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim constr As String
constr = "Provider=sqloledb;Data source=USO-YEGANEH\SQL2008;Initial Catalgo=USO_Final;User Id=sa;Password=123"
Dim conRS As ADODB.Recordset
Set conRS = New ADODB.Recordset
conn.Open constr
With conRS
.ActiveConnection = conn
.Open "Select * from LatLong_Amar"
Sheet1.Range("A1").CopyFromRecordset conRS
.Close
End With
End Sub
I found out what is the problem, it seems full path of the table, despite the fact that database is defined in the Connection String, should be entered. So, the line "Select * from LatLong_Amar" should be changed to [USO_Final].[dbo].[Latlong_Amar]
Sub ConnectionTest()
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim constr As String
constr = "Provider=sqloledb;Data source=USO-YEGANEH\SQL2008;Initial Catalgo=USO_Final;User Id=sa;Password=123"
Dim conRS As ADODB.Recordset
Set conRS = New ADODB.Recordset
conn.Open constr
With conRS
.ActiveConnection = conn
.Open "Select * from [USO_Final].[dbo].[Latlong_Amar]"
Sheet1.Range("A1").CopyFromRecordset conRS
.Close
End With
End Sub
You can do it this way.
Sub ADOExcelSQLServer()
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 = "AdventureWorksLT2012" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [SalesLT].[Customer]" ' 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
With Worksheets("sheet1").Range("a1: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
Here is another option for you to muse over.
Sub TestMacro()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=(local);INITIAL CATALOG=NORTHWIND.MDF;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "SELECT * FROM Categories"
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub

Database connection VB6 to XAMPP

I'm totally new to vb6 and I wanna know why this code does not work. it has runtime 424 error. what do i have to do? whenever i try running it. I can't access the db it says empty. Here's the entire code.
Public cn As ADODB.Connection
Public rs As ADODB.Recordset
Private Sub Form_Load()
Set cn = New ADODB.Connection
cn.ConnectionString = "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=db_Inventory; User=root;Password=;Option=3;"
End Sub
Private Sub Cmd_Add_Click()
If Txt_Pname.Text = "" And Txt_Pprice.Text = "" Then
MsgBox ("Please enter details")
Else
rst.Open "select * from tbl_product", db, adOpenStatic, adLockOptimistic, adCmdText
rs.AddNew
rs("Prod_Name") = Txt_Pname.Text
rs("Prod_Price") = Txt_Pprice.Text
rs.Update
rs.Close
MsgBox ("Product Added!")
End If
End Sub

Resources