Importing values from SQL Server to Excel - excel

I can't import values values from SQL Server to Excel. Can someone please help:
Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
oConn.Open "Provider=SQLOLEDB; " & _
"Data Source=ServerName; " & _
"Initial Catalog=MyDB;" & _
"Trusted_Connection=yes;"
End Sub
Public Sub ExportDataToDB()
Dim rs As ADODB.Recordset
ConnectDB
Set rs = New ADODB.Recordset
Dim strSql As String
strSql = "select t.col1, t.col2 from Table t"
rs.Open strSql, oConn
Sheet1.Range("A2").CopyFromRecordset rs
CloseDBConn
End Sub
Private Sub CloseDBConn()
oConn.Close
End Sub
Connection is successful. No errors. Query is not empty, but nothing is returned into sheet.

In cases where you would like to just read a set of records from the database, such as writing current state of the records to the worksheet you should specify CursorType property of the ADODB.RecordSet as adOpenStatic
Here is the link to Microsoft documention of it: https://learn.microsoft.com/en-us/sql/ado/guide/data/types-of-cursors-ado

Related

Always getting "connection failed" connection sqlserver using VBA

I am trying to connection sqlserver from VBA program, I refer to the following code to achieve it, but I
got the problem: connection failed. Any help. Thank you in advance.
Code:
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 = "EXCEL-PC\EXCELDEVELOPER" ' 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
test this.
Sub cn()
Dim con As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset
Dim i As Integer
con.ConnectionString = "Provider=SQLOLEDB.1;" _
& "Server=(local);" _
& "Database=AdventureWorksLT2012;" _
& "Integrated Security=SSPI;" _
& "DataTypeCompatibility=80;"
con.Open
Set cmd.ActiveConnection = con
cmd.CommandText = "SELECT * FROM [SalesLT].[Customer]"
Set rst = cmd.Execute
Range("A1").CopyFromRecordset rst
con.Close
Set con = Nothing
End Sub
I checked your code and it works for me. So I think it should be a SQL configuration problem e.g. permissions or port issue. You need to test connection status by using sqlserver client and check related connection problem.

VBA excel export to access

Hi I am trying to write a macro that takes the user input from an excel form and adds it to a access table. Using the following code:
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim wsh As Excel.Application
Set cnn = "db.accdb.connection"
Set rst = New ADODB.Recordset
rst.Open "table", cnn, adOpenKeyset, adLockOptimistic, adCmdTableDirect
With rst
.AddNew
.Fields("column1").Value = textboxvar
.Update
End With
with textboxvar previously defined. But it wont work and I don't know why.
after searching for a long time. The top voted post in this thread already answers the question:
Using Excel VBA to export data to MS Access table
This just has to be updated to work with Access 2016:
Public Sub UploadExcel()
Set cn = CreateObject("ADODB.Connection")
dbPath = 'type your database path in here
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.ActiveSheet.Name
scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]"
cn.Open scn
ssql = "INSERT INTO TableName ([Field1], [Field2], [Field3]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql
End Sub
Example that declares, sets, opens connection:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; DataSource='C:\path\databasename.accdb'"
rs.Open "SELECT * FROM MyTable", cn, adOpenKeyset, adLockOptimistic

Querying Excel sheet, find out if rs is empty

I wrote the proc below, and it's working fine, except that I would like to check if the recordset is empty or not. However, rs.EoF and rs.BoF always return False, even if there is no data. What is the trick to make this work ?
Sub PrepData()
Dim ws As Worksheet, wb As Workbook
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim rs2 As ADODB.Recordset
Dim strSql As String, recs As Long
Set wb = ActiveWorkbook
Set ws = ActiveSheet
'create connection
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & wb.FullName & ";" & _
"Extended Properties=""Excel 12.0;HDR=YES"";"
.Open
End With
'check trades without matching couterparty
strSql = "select distinct tf.counterPart from [TradeFile$A3:G5000] tf " & _
"left join [CounterpartiesMapping$] c on tf.counterpart = c.counterpart " & _
"where c.investee is null"
Set rs = cn.Execute(strSql, recs)
'HERE I'd like to see if the recordset is empty,
'but rs.eof and rs.bof are always FALSE regardless of the result
Debug.Print rs.BOF, rs.EOF, rs.RecordCount
ws.Range("p3").CopyFromRecordset rs
rs.Close
cn.Close
End Sub
Have you tried using the RecordCount property for the recordset to find the number of rows returned?
Debug.Print rs.RecordCount
I finally found the solution here:
Just replace
Set rs = cn.Execute(strSql, recs)
By
Set rs = New ADODB.Connection
rs.CursorLocation = adUseCLient
rs.Open strSql, cn
Now Debug.Print rs.BOF, rs.EOF, rs.RecordCount works as expected!

How to copy a powerpivot table down to an excel sheet with vba?

I need to get my table up in the powerpivot model down to the excel worksheet.
So far I have tried to use a Recordset but I cant get an ActiveConnection to the powerpivot table. Is it possible? Or is there an other better way to do this?
I use the following code:
Dim name As ADODB.Recordset
Set name = New ADODB.Recordset
With name
.ActiveConnection = ConnectionName
.Source = "TableName"
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.Open
End With
But with this piece of code I get an error at .ActiveConnection. (Run-time error 3001, it complains about non-allowed connection interval)
This is an example of how to read the records from a named range (assuming 'TableData' is named range).
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 8.0;"
.Open
End With
rs.Open "SELECT * FROM [TableName]", cn
Dim r
For Each r In rs.GetRows
'Do whatever you want per record
Debug.Print r
Next r
rs.Close
cn.Close

Using EXCEL as datasource through Microsoft OLE DB provider

We are frequently using some Excel files as a datasource for massive imports in our database. At the code level, we always refer to the corresponding data source as:
set rs = New ADODB.recordset
rs.open "SELECT * FROM [sheet1$]", myConnectionString, etc
Of course, this procedure only works when there's a sheet in the Excel file which is named [sheet1]. I'd like to add some sheet management code here, but without having to create an instance of the original Excel file, opening it, and so on (my users might get a file with a different sheet name, and might not have Excel installed).
Any idea?
You can open a recordset with the ADO OpenSchema method and then list the table (sheet) names in your workbook.
Public Sub SheetsInWorkbook()
Dim strConnect As String
Dim cn As Object
Dim rs As Object
Dim strPath As String
strPath = CurrentProject.Path & Chr(92) & "temp.xls"
strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source='" & strPath & "';" _
& "Extended Properties='Excel 8.0';"
Set cn = CreateObject("ADODB.Connection")
cn.ConnectionString = strConnect
cn.Open
Set rs = cn.OpenSchema(20) '20 = adSchemaTables '
Debug.Print "TABLE_NAME"
Do While Not rs.EOF
Debug.Print rs!TABLE_NAME
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub

Resources