Copy rows from access table to Excel - vba

I have the following code
Private Sub CommandButton1_Click()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\ActionList.accdb"
strSql = "SELECT * FROM Actionlist;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
My purpose is to get all rows from a certain table to copy in my Excel sheet. I though something this easy would be all over the internet, but I cannot seem to find it. I would like the rows to start from A2, since I've already added the access table to my worksheet by using the built-in function of Excel. I want to do this manually however, to add certain filters.

You will need, what you have, but also
for f= 0 to rs.fields.count-1
range("a1").offset(0,f).value=rs.fields(f).name
next f
range("a2").copyfromrecordset rs

Switch do DAO, so that CopyFromRecordset() will work:
Private Sub CommandButton1_Click()
Dim Dbs As DAO.Database
Dim rs As DAO.Recordset
Dim strSql As String
Set Dbs = OpenDatabase("C:\ActionList.accdb")
strSql = "SELECT * FROM Actionlist;"
Set rs = Dbs.OpenRecordset(strSql)
'Add Head lines:
for i= 0 to rs.fields.count-1
range("a1").offset(0,i).value=rs.fields(i).name
next f
'Add Data:
range("a2").CopyFromRecordset rs
'Colse resources:
rs.Close
Set rs = Nothing
Dbs.Close
Set Dbs= Nothing
End Sub

Related

'Application.Transpose(rs.GetRows)' type mismatch error Nº 13 in SQL/VBA code

I'm trying to export data from an Oracle Database through VBA, and I'm getting an error Nº 13 Type Mismatch at line:
mtxData = Application.Transpose(rs.GetRows)
below is my entire code
Sub start()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim mtxData As Variant
Dim strSQL As String
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open ( _
"user ID =user" & _
";Password=password" & _
";data source=source" & _
";Provider=OraOLEDB.oracle")
rs.CursorType = adOpenForwardOnly
strSQL = ("SELECT * FROM table")
rs.Open strSQL, cn
mtxData = Application.Transpose(rs.GetRows)
ActiveSheet.Range("A1:K22") = mtxData
below is the result I was expecting...
You will get a type mismatch error from Transpose if the data you received via GetRows contains any null values.
There is, however, a better way to dump the data you have in a RecordSet into Excel: Simply use the method Range.CopyFromRecordSet. Advantage is you don't need the transpose, and you need to specify only the start cell.
Const connStr = "(Your connection String)"
Const sql = "(Your SQL)"
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
cn.Open connStr
Set rs = cn.Execute(sql)
With ActiveSheet
.UsedRange.Clear
.Range("A1").CopyFromRecordset rs
End With
If you need also the column names, try this:
With ActiveSheet
.UsedRange.Clear
Dim destRange As Range, colIndex As Long
Set destRange = .Range("A1")
' Write column names
For colIndex = 0 To rs.Fields.Count - 1
destRange.Offset(0, colIndex) = rs(colIndex).Name
Next colIndex
' Dump the data
destRange.Offset(1, 0).CopyFromRecordset rs
End With

Access Table to Specific Excel Spreadsheet

I am having problem with copying records from an Access table to an excel worksheet using Excel vba.
After the docmd opens the table I'm lost!!!!!!
Can someone help Pleassssssseeeeee?
Thanks
Here is my code:
Sub OpenAccessDB()
Dim DBFullPath As String
Dim DBFullName As String
Dim TableName As String
Dim TargetRange As Range
Dim appAccess As Object
Dim RS As New ADODB.Recordset
'File Paths and Names*********************************
DBFullPath = "e:\ccampbellStuff\"
DBFullName = "2015_02.accdb"
TableName = "Record Opt Outs"
'Initiating the Access DB Engine**********************
Set appAccess = CreateObject("Access.Application")
'Opening the database
appAccess.OpenCurrentDatabase (DBFullPath & DBFullName)
appAccess.Visible = True
'Open Access Table Called Record Opt Outs****
**appAccess.DoCmd.Opentable (TableName)**
'Set RS = appAccess.DoCmd.Opentable (TableName) this didnt work either
'Set appAccess = Nothing
'Copy Access Records and Patse to Excel''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Close database
appAccess.Quit
End Sub
I wouldn't bother automating Access itself - just use ADO:
Sub loadAccessData()
'////////////////////////////////////////////////////////////////////
' requires a reference to a Microsoft ActiveX Data Objects Library.
'////////////////////////////////////////////////////////////////////
Dim cn As ADODB.Connection
Dim sQuery As String
Dim rs As ADODB.Recordset
Dim sDB_Path As String
Dim ws As Worksheet
' output to activesheet
Set ws = ActiveSheet
' Path to database
sDB_Path = "c:\somepath\database1.accdb"
Set cn = New ADODB.Connection
' open connection to database
With cn
.CursorLocation = adUseServer
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & sDB_Path & ";"
.Open
End With
' SQL query string - change to suit
sQuery = "SELECT * FROM tblTest"
' Create New Recordset
Set rs = New ADODB.Recordset
' open recordset using query string and connection
With rs
.Open sQuery, cn, adOpenStatic, adLockPessimistic, adCmdText
' check for records returned
If Not .EOF Then
'Populate field names
For i = 1 To .Fields.Count
ws.Cells(1, i) = .Fields(i - 1).Name
Next i
' Load data starting at A2
ws.Cells(2, 1).CopyFromRecordset rs
End If
.Close
End With
' clean up
cn.Close
End Sub

Excel automation error when running SQL update statement

I have the following code that is intended to update an Access database however when i run the macro i get an automation error. If i execute the SELECT statement, it runs fine. I don't need to select any values from the worksheet to update the database.
Private Sub UpdateRecord()
ThisWorkbook.Activate
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\temp\test.mdb"
strSql = "UPDATE table1 SET Name1='Test' WHERE Object_ID=2076;"
'strSql = "SELECT * FROM table1;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
Worksheets("Sheet1").Select
Sheets("Sheet1").Range("A6").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Unfortunately I cannot repeat your situation and use ADODB. I recommend you to use native DAO library to work with MSJet (Access) database.
Sub qwe()
Dim dbe As New DAO.DBEngine
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Set dbs = dbe.OpenDatabase("C:\Users\nmaksudov\Documents\Database2.accdb")
dbs.Execute("UPDATE Table1 SET Field2='zzz' WHERE Field1=2")
Set rst = dbs.OpenRecordset("select * from Table1")
While Not rst.EOF
MsgBox rst.Fields(1).Value & "," & rst.Fields(2).Value
rst.MoveNext
Wend
MsgBox rst.RecordCount
End Sub
This should work perfect. Just add DAO library of correct version to your project. To find correct library open VBA editor in Access and choose Tools/References… menu. Find data access library in the list (in my case it is «Microsoft Office 12.0 Access database engine Object Library» or it could be «DAO 3.6» etc. Depens on version). After that open the same dialog in Excel and add the the object library.

Why ADO VBA code returns only 6559 records?

I try to make macro that operate with sql statements with ADO liblary, but actually it returns only 6559 records, while one of my table have 72k records.
Why?
Recently, I've noticed, that actually my code does not returns 6559, but rows number - 65537. So when I decrease number of the rows in sheet to 72092, I even gets less rows (6550).
Another thing I noticed is that rs.RecordCount returns "-1".
Here is code for my subproccedure. It have three parameters: sql statement (sqlstmt), destination sheet name (sheet_name) and destination range (destination1).
'subprocedure that execute sql statements and save resault in given worksheet
Public Sub sql_query(ByVal sqlstmt As String, ByVal sheet_name As String, ByVal destination1 As String)
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim connstring As String
Dim qt As QueryTable
Dim tw_path As String
Dim is_name As Boolean
Dim sh As Worksheet
'''making sheet if it doesn't exist
is_name = False
For Each sh In ThisWorkbook.Worksheets
If sh.Name = sheet_name Then is_name = True
Next
If is_name = False Then ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)).Name = sheet_name
''' connection
tw_path = ThisWorkbook.path & "\" & ThisWorkbook.Name
connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & tw_path & ";Extended Properties=Excel 8.0;Persist Security Info=False"
Set conn = New ADODB.Connection
conn.ConnectionString = connstring
conn.Open
'''executing statement
Set rs = New ADODB.Recordset
rs.Source = sqlstmt
rs.ActiveConnection = conn
rs.Open
'''saving records
ThisWorkbook.Worksheets(sheet_name).Activate
Set qt = Worksheets(sheet_name).QueryTables.Add(Connection:=rs, Destination:=Range(destination1))
qt.Refresh
'''end
If rs.State <> adStateClosed Then rs.Close
conn.Close
If Not rs Is Nothing Then Set rs = Nothing
If Not conn Is Nothing Then Set conn = Nothing
Set qt = Nothing
End Sub
Thanks for help
I'm guessing you are using excel 2003 or a prior version, in which case a worksheet has a maximum of 65,536 rows. I would've put this in a comment instead of an answer but I'm 1 rep short of being able to comment :(. Sorry

SQL Select query in Excel VBA

I have email addresses on Sheet 1 cell A1:A735. I need to use those cell data in a where clause. Currently it is hardcoded. I am fetching data from Sql and want to paste data in Active range A1.
I cannot figure out how to loop through.
Sub GetDataFromADO()
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyRecordset As ADODB.Recordset
Dim Email2 As Range
Dim Worksheet1 As Worksheet
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
objMyConn.ConnectionString = "some connection string ;"
objMyConn.Open
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = "SELECT * FROM [abc].[dbo].[excusers] where email = 'asif#gmail.com'"
objMyCmd.CommandType = adCmdText
Set objMyRecordset.Source = objMyCmd
objMyRecordset.Open
ActiveSheet.Range("a1").CopyFromRecordset objMyRecordset
End Sub
You can loop through the cells like so:
With Sheet1
For i = 1 To 735
sText = "SELECT * FROM [abc].[dbo].[excusers] where email = '" _
& Replace(.Cells(1, i), "'", "''") & "'"
objMyCmd.CommandText = sText
Next
End With
This should give you a way to call a subroutine the connects for you. You would pass in the parameters required.
Sub adocnnRoutine_SP(ByVal ReturnVal As String, ByVal cnnstr As String, ByVal CallVal As Range, Optional CallHDR As Range)
'ReturnValue is the string to send to SQL Such as "Select * from TableName where email = 'username#email.com'"
'CallVal places the results in that one cell as a starting point Such as Sheet2.Range("A2")
'CallHDR is optional header placement point Such as Sheet2.Range("A1")
Dim cn As ADODB.Connection, rs As ADODB.RECORDSET
Set cn = New ADODB.Connection
Set rs = New ADODB.RECORDSET
On Error GoTo CleanUp
cn.Open cnnstr
rs.Open ReturnVal, cnnstr
If Not CallHDR Is Nothing Then
With CallHDR
For Each field In rs.Fields
.Offset(0, Offset).Value = field.Name
Offset = Offset + 1
Next field
End With
End If
CallVal.CopyFromRecordset rs
CleanUp:
Debug.Print Err.Description
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
And Then you can loop through your sheet1 emails as required.