Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

GetRows Function and Exporting Data

Introduction

We are going to create a useful data export utility with the GetRows() method of the Recordset Object. The GetRows method is used for loading the entire set of data from table into memory in a doubly dimensioned Variant Array with a single statement. Let us try it with an example to see how this is done? An image of a sample table is given below and we will see how this will look like in memory when loaded with the help of GetRows() method of the Recordset Object:

Table: Employees
ID Name BirthDate Height Weight
1 Nancy 12/10/1980 164 58
2 Peter 05/07/1975 180 80
3 Linda 17/11/1982 170 60

The VBA Code.

The following sample VBA Routine loads the above data into memory and a listing is dumped in the Debug Window:

Public Function Test(ByVal tblName As String)
Dim db As Database, rst As Recordset, varData As Variant
Dim intFields As Integer, intRecords As Integer, j As Integer, k As Integer
Dim rec As String, fld_type As Integer

Set db = CurrentDb
Set rst = db.OpenRecordset(tblName, dbOpenTable)
j = rst.RecordCount - 1
k = rst.Fields.Count - 1

varData = rst.GetRows(j + 1)

For intRecords = 0 To j
    rec = ""
    For intFields = 0 To k
    fld_type = rst.Fields(intFields).Type

    If fld_type = 11 Or fld_type = 12 Then
      GoTo nextField
    End If
      rec = rec & varData(intFields, intRecords) & ","
nextField:
    Next
    rec = Left(rec, Len(rec) - 1)
    Debug.Print rec
Next
rst.Close
Set rst = Nothing
Set db = Nothing
End Function

The arrangement of records in memory in a two dimensional array looks like the following:

1 2 3
Nancy Peter Linda
12/10/1980 05/07/1975 17/11/1982
164 180 170
58 80 60

The Memory Image of Data.

The records are not arranged in row order as they appear in datasheet view, instead they are loaded in columns.  So, after loading the data in memory we must know how to address the two dimensional array to access each record in correct order to output the data.  Each field value is separated with a comma in the listing provided in the Debug window.

Normally, in a two dimensional Array the first index value of the array is the row number and the second one is column number.  But, in this case the first index value is the Field order Number and the second value is the Record Number.  You can check the sample data arrangement in memory shown above.


Export Data in Text Format

We will write a small utility program to export any MS-Access Table into comma delimited Text/CSV File, so that the data can be easily transported through internet or to import into other Applications.

The VBA Code of the program is given below:

Public Function CreateDelimited(ByVal xtableName As String, ByVal txtFilePath As String)
'-----------------------------------------------------
'Utility: CreateDelimited()
'Author : a.p.r.pillai
'Date   : Dec. 2010
'Purpose: Create Comma Delimited Text File from Table 
'Rights : All Rights Reserved by www.msaccesstips.com
'-----------------------------------------------------
Dim db As Database, rst As Recordset
Dim varTable() As Variant, j As Long, k As Long
Dim rec As String, fld_type As Integer
Dim intRecords As Integer, intFields As Integer

Set db = CurrentDb
Set rst = db.OpenRecordset(xtableName, dbOpenTable)
varTable = rst.GetRows(rst.RecordCount)
k = rst.Fields.Count - 1
j = rst.RecordCount - 1

Open txtFilePath For Output As #1
rec = ""
For intFields = 0 To k
   fld_type = rst.Fields(intFields).Type
        If fld_type = 11 Or fld_type = 12 Then GoTo nextField
   rec = rec & Chr$(34) & rst.Fields(intFields).Name & Chr$(34) & ","
nextField:
Next
rec = Left(rec, Len(rec) - 1)
Print #1, rec
For intRecords = 0 To j
    rec = ""
    For intFields = 0 To k
        fld_type = rst.Fields(intFields).Type
        If fld_type = 11 Or fld_type = 12 Then GoTo Next_Field
        rec = rec & IIf(fld_type = 10, Chr$(34) & varTable(intFields, intRecords) & Chr$(34), varTable(intFields, intRecords)) & ","
Next_Field:
        Next: rec = Left(rec, Len(rec) - 1)
        Print #1, rec
Next
Close #1
rst.Close

Set rst = Nothing
Set db = Nothing

End Function

The Utility can be called from a Command Button Click Eventprocedure after setting the Table name and the target file pathname in text boxes.  You can test the utility by calling it from the Debug Window (Immediate Window) directly as given below:

CreateDelimited "Products", "C:\Temp\Products.txt"

NB: If MEMO or Photo Fields are present in the Table they are excluded from the output file.

The target file extension can be either .TXT or .CSV.

Share:

1 comment:

  1. [...] security, Internet, dynamic queries/reports, Mail-merge. MsgBox with Office Assistant. … Read the rest of content…… stLight.options({publisher:'af88d10d-4ec4-486e-8284-c263218fb2dd'}); RELATED [...]

    ReplyDelete

Comments subject to moderation before publishing.

MS-Access Tips on your Finger-Tip

  • Download Android App 'MSA Guru' Version of LEARN MS-ACCESS TIPS AND TRICKS from Google Play Store.

Want to Post Free Ads on the Web


Translate



PageRank
Subscribe in a reader
Your email address:

Delivered by FeedBurner

Search

Popular Posts

Blog Archive

Powered by Blogger.

Follow by Email

Labels

Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Class Module External Links Queries Array msaccess reports Accesstips WithEvents msaccess tips Downloads Objects Menus and Toolbars Collection Object MsaccessLinks Process Controls Art Work Property msaccess How Tos Combo Boxes Dictionary Object Graph Charts Query VBA msaccessQuery Calculation Event List Boxes Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference TreeView Control ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button ImageList Control Report msaccess menus msaccessprocess security advanced Access Security Add Auto-Number Field Type Form Instances ImageList Item Macros Menus Nodes RaiseEvent Recordset Top Values Variables Wrapper Classes msaccess email progressmeter Access2007 Copy Excel Export Expression Fields Join ListView Control Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility Workgroup database function msaccess wizards tutorial Access Emails and Alerts Access Fields Access How Tos Access Mail Merge Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Common Controls Conditional Formatting Data Filtering Database Records Defining Pages Diagram Disk Dynamic Lookup Error Handler External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code