Export Data From MS Access to MS Excel ListBox - sql

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

Related

VBA SQL Query only returns numeric values

I have a program designed to re-transcribe a text file into MS Excel using a VBA macro with an SQL query using ADODB.
The text file is itself an extract from a database from another department(and is presented as a comma separated table in the text file).
Anyway, I have a column ('Group' below) filed with either 'Z4' or '50'. These are the only two types of input for said column.
Until today, the query returned both values. Now, I only get '50'. The cells where 'Z4' ought to appear are empty.
Code is below:
Sub TextReader()
'Text reader
Application.ScreenUpdating = False
'Error Management
On Error Resume Next
'--------- Connection -------------------------------
Dim cnn As ADODB.Connection
Dim str As String
Set cnn = New ADODB.Connection
cnn.Provider = "Microsoft.ACE.OLEDB.12.0" '
cnn.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ";" & _
"Extended Properties=""text; HDR=YES; FMT=Delimited;"""
'Open Connection
cnn.Open
'ADODB record
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
'cleanup
Sheets("Cost").Cells.Clear
'SQL String
str = "select Group from ZR46.txt "
'Get the values
With rs
.ActiveConnection = cnn
.Open str
Sheets("Cost").Range("A2").CopyFromRecordset rs
.Close
End With
'Close
cnn.Close
Application.ScreenUpdating = True
End Sub
The text file (not exactly that, but modified because it's private data):
,Article,Designation,Price,Strat,Group,Provis,
,123456789,BODY,706§09,PD,Z4,COND,
,897654321,BONNET,1§456§15,PD,Z4,COND,
,123789456,STEM,102§06,PD,50,COND,

VBA DAO Accessing Excel 2010 like database

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

How can I query specific columns in a VBA macro used to transfer data across workbooks?

I'm using a Excel macro to transfer data between works with ADO by following these guidelines. Currently, I've set up the code to search for a keyword in column A of the source file. Once it finds the keyword, it will copy data from that entire row. However, I only need data from columns G-I, and cannot find the information to condense the data selection.
Public Sub MoveData()
'defines the project name as a variable
Dim fileName As String
fileName = Worksheets("Cover").Range("B5").Value
'defines the path
Dim path As String
path = "C:\Users\(user)\Documents\(folder)\" & fileName & ".csv"
'defines the two workbooks that the data will move between
Dim currentWB As Workbook
Set currentWB = ThisWorkbook
Dim openWB As Workbook
Set openWB = Workbooks.Open(path)
Dim openWs As Worksheet
Set openWs = openWB.Sheets(fileName)
'connects using ADODB to transfer the data
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & path & ";" & _
"Extended Properties=Excel 12.0 Xml;"
.Open
End With
'selects the first column to be read and sorted
Dim subCell As Range
Dim myRange As Range
Set myRange = Range("A1:A500")
Dim cmdOpen As Boolean
cmdOpen = False
For Each subCell In myRange
'searches for the column markups
If subCell Like "*COLUMN*" Then
strQuery = "SELECT * FROM [" & fileName & "$] Where Subject = '" & subCell.Value & "'"
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = cn
.CommandText = strQuery
End With
Dim rst As New ADODB.Recordset
With rst
If cmdOpen = False Then
.Open cmd
cmdOpen = True
End If
End With
currentWB.Worksheets("Cols").Range("B7:D7").CopyFromRecordset rst
End If
Next subCell
openWB.Close
End Sub
This strQuery = "SELECT * FROM [" & fileName & "$] Where Subject = '" & subCell.Value & "'" is the line I am referring to. It selects the row of data where the keyword is found. I want to limit this selection to columns G-I. Any advice on how I could accomplish this would be greatly appreciated.

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

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