VBA DAO Accessing Excel 2010 like database - vba

I am trying to use DAO to write some VBA into Excel 2010. I want to be able to access an excel 2010 workbook like a database. I am trying to open a workbook instead of a mdb file. Is there any way I can use DAO with an excel workbook instead of an actual database?
Dim db As Database
Dim rst As Recordset
Dim SQL As String
SQL = "SELECT * From [DataSheet$]"
Set db = OpenDatabase(ThisWorkbook.FullName)
Set rst = db.OpenRecordset(SQL)
'displays the first record and first field
MsgBox rst.Fields(0)
'close the objects
rst.Close
db.Close
'destroy the variables
Set rst = Nothing
Set db = Nothing
I borrowed code from here http://www.excel-spreadsheet.com/vba/dao_ado.htm

Actually, you can connect to Excel workbooks using DAO by extending the arguments of DAO.OpenDatabase():
Dim conn As Object, db As Object, rst As Object
Set conn = CreateObject("DAO.DBEngine.120")
' EXCEL OLDER VERSION
Set db = conn.OpenDatabase("C:\Path\To\Excel_Workbook.xls", False, True, "Excel 8.0;HDR=Yes;")
' EXCEL CURRENT VERSION
Set db = conn.OpenDatabase("C:\Path\To\Excel_Workbook.xlsx", False, True, "Excel 12.0 Xml;HDR=Yes;")
Set rst = db.OpenRecordset("SELECT * FROM [SheetName$]")
MsgBox rst.Fields(0)
rst.Close
db.Close
Set db = Nothing
Set conn = Nothing
Set rst = Nothing

I figured out my issue. Using the code below you can access an excel file and treat it like a database.
Option Explicit
Private Sub btnConnect_Click()
Dim dataConection As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim SQL As String
Dim DBPath As String
Dim connectionString As String
DBPath = ThisWorkbook.FullName 'Refering the sameworkbook as Data Source
'You can provide the full path of your external file as shown below
connectionString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
'Open connection
dataConection.Open connectionString
'Create SQL query
SQL = "SELECT * From [DataSheet$]"
'Open record set (query or table, connection)
mrs.Open SQL, dataConection
Do While Not mrs.EOF
Debug.Print " " & mrs!Name
mrs.MoveNext
Loop
mrs.Close
'Close Connection
dataConection.Close
End Sub

Related

Export Data From MS Access to MS Excel ListBox

I have a working VBA code that exports data from MS Access data and pastes it into MS Excel Sheet cells and using cell range as RowSource to appear data in the ListBox.
Is there a way to paste directly the imported data into ListBox instead of pasting into Sheet cells?
Sub IBDocsLibSearch()
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rs As ADODB.Recordset 'dim the ADO recorset class
Dim dbPath As String
Dim MyDbPassword As String
Dim SQL As String
Dim i As Integer
Dim var1
Application.ScreenUpdating = False
IBDocLibSheet.Range("A2:I500000").ClearContents
dbPath = LinkSheet.Range("C4").Value 'Inbound Checklist Database Location
MyDbPassword = PWSheet.Range("C3").Value 'Password to connect the Excel to Access
Set var1 = IBUserForm.IBDTextSerialNo
'Initialise the collection class variable
Set cnn = New ADODB.Connection
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath & ";Jet OLEDB:Database Password=" & MyDbPassword
SQL = "SELECT * FROM DB_IBDocuments WHERE SerialNo = '" & var1.Value & "'"
Set rs = New ADODB.Recordset
rs.Open SQL, cnn
If rs.EOF And rs.BOF Then
'Close the recordset and connection
rs.Close
cnn.Close
'Clear Memory
Set rs = Nothing
Set cnn = Nothing
Application.ScreenUpdating = True
Exit Sub
End If
IBDocLibSheet.Range("A2").CopyFromRecordset rs '----This is where to paste the extracted data
'To show results in Listbox
IBUserForm.IBDListBox.RowSource = "IBL_DocLib"
'Close the recorset and connections
rs.Close
cnn.Close
'Clear memory
Set rs = Nothing
Set cnn = Nothing
Application.ScreenUpdating = True
End Sub

Query range in activeworkbook using ADODB

I'm trying to write some VBA that can query a named range in VBA using SQL. Currently, it works reasonably well, but i have the problem that every time i run the macro a read-only instance of the worksheet is opened. I want to use the macro to query ranges within the same workbook without opening a read-only copy.
Here is my code
Public Sub QueryAndOutputToCell(ByVal query As String, rng As Range)
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim DBFullName, connString, SQL As String
DBFullName = ThisWorkbook.path & "\" & ThisWorkbook.name
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & DBFullName & "';Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"
conn.connectionString = connString
conn.Open ' Read-only copy is opened here
conn.commandtimeout = 0
Dim cubeData As ADODB.Recordset
Set cubeData = New ADODB.Recordset
cubeData.Open query, conn, adOpenDynamic, adLockReadOnly
rng.CopyFromRecordset cubeData
cubeData.Close
conn.Close
Set cubeData = Nothing
Set conn = Nothing
End Sub
Do anyone know if this is possible?

Saving Results of Access Query To Worksheet Excel VBA

I cant seem to find an easy way of doing outside of just accessing the SQL from ACCESS SQL View and doing it manually. Is there some magic way to use this code below and do that?
Its worth pointing out that I am trying to do this from Excel's VBA.
Private Sub tryagain()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
With con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open "C:\Users\Ashleysaurus\Desktop" & "\" & "xyzmanu3.accdb"
End With
con.Execute "Invoice Query"
'How do output to Worksheet?
rs.Close
cmd.ActiveConnection.Close
End Sub
Simply use the ADO recordset object which you initialize, call the query, and then run the Range.CopyFromRecordset method (specifying the leftmost worksheet cell to place results).
Also, see the changed connection open routine with proper connection string. And because recordsets do not pull in column headers automatically but only data, an added loop was included iterating through recordset's field names.
Private Sub tryagain()
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConnection As String
Dim i as Integer, fld As Object
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='C:\Users\Ashleysaurus\Desktop\xyzmanu3.accdb';"
con.Open strConnection
rs.Open "SELECT * FROM [Invoice Query]", con
' column headers
i = 0
Sheets(1).Range("A1").Activate
For Each fld In rs.Fields
ActiveCell.Offset(0, i) = fld.Name
i = i + 1
Next fld
' data rows
Sheets(1).Range("A2").CopyFromRecordset rs
rs.Close
cn.Close
End Sub
By the way, this same above setup can even query Excel workbooks as the Jet/ACE SQL Engine is a Windows technology (.dll files) available to all Office or Windows programs.
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='C:\Path\To\Workbook.xlsm';" _
& "Extended Properties=""Excel 8.0;HDR=YES;"";"
strSQL = "SELECT * FROM [Sheet1$]"

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.