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 the 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 the 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 the Data.

The records are not arranged in row order as they appear in the datasheet view, they are loaded in columns instead.  So, after loading the data in memory we must know how to address the two-dimensional array to access each record in the 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 the 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 the memory shown above.

Export Data in Text Format

We will write a small utility program to export any MS-Access Table into a comma-delimited Text/CSV File, so that the data can be easily transported through the 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 Event procedure 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.

Earlier Post Link References:

Share:

Create Menus with Macros-2

Continued from Create Menus with Macros. - Access 2003

Continued from last week's Article: Create Menus with Macros, please go through it before continuing.

Last week we learned how to create a simple Shortcut Menu for Forms with Macros.  This week we will create a Toolbar Button and a Menu Bar item through Macro-based Menus.

New Macro: macProcess.

But, before all that, let us make a little modification to our earlier shortcut menu to add a menu group item added with a few options.

  1. Open a new macro in the design view.

  2. Select MsgBox from the drop-down list in the Action Column.

  3. Type Proceed with Report Data Processing? In the Message control under the Action Argument list.

  4. Select Critical from the drop-down list in the Type control.

  5. Type Report Processing in the Title control.

    Note: This macro is supposed to contain a series of actions; like running action queries (Make-Table, Append, Update, Delete, or running of other macros or VBA Routines) to prepare data ready for Reports.  Here, we are simply adding a message box to display a message instead.  You must create Menus with actions as per the requirements of your Application.

  6. Save the Macro with the name: macProcess and close it.

    The macSubMenu Macro.

  7. Click on New to open another new macro in Design View.

  8. If the Macro Name Column is not visible then select Macro Name from View Menu.

  9. Type &Form in the Macro Name column of the first row and select OpenForm from the drop-down list under the Action Column.

  10. Select an existing Form in the From Name control using the drop-down control.

  11. Type Process &Data in the Macro Name column in the second row and select the RunMacro in the Action Column.

  12. Type macProcess (or select it from the drop-down list) to insert the process macro that we have created in step 6.

  13. Type &Report in the Macro Name column in the third row and select OpenReport in the Action column.

  14. Select an existing Report from your application in the Report Name control.

  15. Select Print Preview in the View control.

  16. Save the macro with the name macSubMenu and close it.

    Modify Macro: mcrShortCut

  17. Open the macro mcrShortCut that we have created last week.

  18. Type MenuGroup in the next row (as shown in the image given below) and select the AddMenu option from the drop-down list under the Action column.

  19. Type Form/Report in the Menu Name control below the Action Arguments.

  20. Type macSubMenu (or select from the drop-down list) in the Menu Macro Name control.

  21. Save and close the macro mcrShortCut.

  22. If you remember on which Form you have attached the earlier macro Shortcut Menu last week, then you can open that Form in normal view and right-click on the Form to display the Form/Report Sub-Menu we added to the earlier menu. If You don't remember then open one of your existing Forms in Design View.

  23. Display the Property Sheet (View - -> Properties or press ALT+Enter).

  24. Click on the Other Tab.

  25. Set the Shortcut Menu Property value to Yes.

  26. Set the Shortcut Menu Bar Property value to macMenu (you can select the macro from the drop-down list also).

  27. Save and close the Form.

    The Shortcut Menu Trial Run.

  28. Open the Form in Normal View.

  29. Right-Click on a field to display the Shortcut Menu. The new Group Menu that we have added will appear at the end of the Menu with the description Form/Report.

  30. Place the mouse over the Form/Report menu group to display its Sub-Menu items.

The menu definition now remains in Macros and we are directly using it on Forms.  But, we can convert the Menu Macro into a regular:

  • Menu Bar (like File, Edit, etc.) OR
  • Toolbar  OR
  • Shortcut Menu.

If you would like to convert this macro menu into a Menu Bar then we must make a small change in the macMenu macro.

Converting Macro into Menu Bar.

  1. Open macMenu in design view.

  2. Type myMenu in the Menu Name control under Action Arguments.

  3. Save and close the macro.

  4. Click on the macMenu macro to select it.

  5. Highlight the Macro in Tools Menu.

  6. Click on Create Menu from Macro Option.

    A Menu Bar will appear on top with the label myMenu.

  7. Click on myMenu option to display the menu options, which we have created macros.

Note: You should not attempt to convert the same macMenu to a Toolbar Menu; a name conflict will take place.

Quick Toolbar Button.

Tip: To create a quick Toolbar Button with the same set of macros, do the following:

  1. Make a copy of the macros: macMenu, mcrShortCut, and macSubMenu and name them as mac_Menu, mcr_ShortCut, and mac_SubMenu.

  2. Open mcr_ShortCut macro in design view.

  3. Click on the last line and change the Menu Macro Name control value to mac_SubMenu, save, and close the Macro.

  4. Open the mac_Menu macro in the design view.

  5. Change the Menu Name control value to myToolbar.

  6. Change the Menu Macro Name control value to mcr_ShortCut, save, and close mac_Menu Macro.

  7. Click on the mac_Menu Macro to select it.

  8. Highlight Macro in Tools Menu to display its Options.

  9. Click on Create Toolbar from the Macro option to convert the macro into a Toolbar; the myToolbar button will appear near the existing Toolbar with the label myToolbar.

  10. You may click on it to display the Menu.

Share:

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

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 ListView Control Query VBA msaccessQuery Calculation Event Graph Charts ImageList Control List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button 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 Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility WScript 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 Desktop Shortcuts Diagram Disk Dynamic Lookup Error Handler External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Message Box 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