Examples for Exporting Access table or query to EXCEL Workbook Files Part 2

Create a Query and Export multiple “filtered” versions of a Query (based on data in another table) to separate EXCEL files via TransferSpreadsheet (VBA)

Generic code to create a temporary query, get list of filtering values, and then loop through the list to filter various data and export each filtered query to separate EXCEL files. In this sample code, the employees assigned to each manager are exported to separate EXCEL files, one file for each manager.


Dim qdf As DAO.QueryDef
Dim dbs As DAO.Database
Dim rstMgr As DAO.Recordset
Dim strSQL As String, strTemp As String, strMgr As String

Const strQName As String = "zExportQuery"
Note:

Set dbs = CurrentDb

‘ Create temporary query that will be used for exporting data;
‘ we give it a dummy SQL statement initially (this name will
‘ be changed by the code to conform to each manager’s identification)
strTemp = dbs.TableDefs(0).Name
strSQL = “SELECT * FROM [” & strTemp & “] WHERE 1=0;”
Set qdf = dbs.CreateQueryDef(strQName, strSQL)
qdf.Close
strTemp = strQName

‘ *** code to set strSQL needs to be changed to conform to your
‘ *** database design — ManagerID and EmployeesTable need to
‘ *** be changed to your table and field names
‘ Get list of ManagerID values — note: replace my generic table and field names
‘ with the real names of the EmployeesTable table and the ManagerID field
strSQL = “SELECT DISTINCT ManagerID FROM EmployeesTable;”
Set rstMgr = dbs.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)

‘ Now loop through list of ManagerID values and create a query for each ManagerID
‘ so that the data can be exported — the code assumes that the actual names
‘ of the managers are in a lookup table — again, replace generic names with
‘ real names of tables and fields
If rstMgr.EOF = False And rstMgr.BOF = False Then
rstMgr.MoveFirst
Do While rstMgr.EOF = False

‘ *** code to set strMgr needs to be changed to conform to your
‘ *** database design — ManagerNameField, ManagersTable, and
‘ *** ManagerID need to be changed to your table and field names
‘ *** be changed to your table and field names
strMgr = DLookup(“ManagerNameField”, “ManagersTable”, _
“ManagerID = ” & rstMgr!ManagerID.Value)

‘ *** code to set strSQL needs to be changed to conform to your
‘ *** database design — ManagerID and EmployeesTable need to
‘ *** be changed to your table and field names
strSQL = “SELECT * FROM EmployeesTable WHERE ” & _
“ManagerID = ” & rstMgr!ManagerID.Value & “;”
Set qdf = dbs.QueryDefs(strTemp)
qdf.Name = “q_” & strMgr
strTemp = qdf.Name
qdf.SQL = strSQL
qdf.Close
Set qdf = Nothing

‘ Replace C:\FolderName\ with actual path
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
strTemp, “C:\FolderName\” & strMgr & Format(Now(), _
“ddMMMyyyy_hhnn”) & “.xls”
rstMgr.MoveNext
Loop
End If

rstMgr.Close
Set rstMgr = Nothing

dbs.QueryDefs.Delete strTemp
dbs.Close
Set dbs = Nothing

Solving problems with Dates in SQL

It’s important to remember that regardless of where you are using Access, if doing SQL from code you need your dates to be in US format dates eg:


" WHERE DateField >= #" & Format$(startDate, "mm/dd/yyyy") & "#"

Examples for Exporting Access table or query to EXCEL Workbook Files Part 1

Create and Export a
Parameter Query to EXCEL file via TransferSpreadsheet (VBA)

Generic code to generate “on the fly” a query that uses one or more controls on
an open form as parameters, and then export that query to an EXCEL file. This
example concatenates the parameter values into the generated SQL statement and
then saves the query so that it can be exported. The query then is deleted after
the export is completed.

 

Dim dbs As DAO.Database
Dim qdfTemp As DAO.QueryDef
Dim strSQL As String, strQDF As String
Set dbs = CurrentDb

‘ Replace NameOfTableOrQuery with the real name of the table or query,
‘ replace NameOfForm with the real name of the form, and replace
ADateControlOnForm and AnotherDateControlOnForm with the real names

strSQL = “SELECT NameOfTableOrQuery.* FROM NameOfTableOrQuery ” & _   
“WHERE NameOfTableOrQuery.FieldName >= ” & _     
Format(Forms!NameOfForm!ADateControlOnForm.Value,”\#mm\/dd\/yyyy\#”) & _     
” And NameOfTableOrQuery.FieldName <=” & _     
Format(Forms!NameOfForm!AnotherDateControlOnForm.Value,”\#mm\/dd\/yyyy\#”) &
“‘;”

‘ of the controls on that form

strQDF = “_TempQuery_”
Set qdfTemp = dbs.CreateQueryDef(strQDF, strSQL)
qdfTemp.Close
Set qdfTemp = Nothing

‘ Replace C:\MyFolderName\MyFileName.xls with the real path and
filename for the
‘ EXCEL file that is to contain the exported data

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
      strQDF,”C:\MyFolderName\MyFileName.xls”

dbs.QueryDefs.Delete strQDF
dbs.Close
Set dbs = Nothing

By Ken Snell 

Dev Tip of the Week: How to search by driving time with AJAX v7, REST, and Spatial Data Services

The recently released Query API within the Bing Spatial Data Services makes it easy to build applications that enable searching for locations by area, by property, and by ID. A common scenario is the ‘Locator’ application, in which end-users enter an address, and find the locations that are nearest to them. We can easily cater for this in Bing Maps by geocoding the end-user’s address with the Locations API, and then finding nearby locations with the Query API to Query by Area.  Using a spatial filter, we can find the locations that sit within a specified radius of the given location, and present the results ordered by distance ‘as the crow flies’.

But what about those cases in which geography or other considerations mean that the closest location by straight line measurement will actually take much longer to drive to than one of the other locations? For example, if you are in the Upper West Side of Manhattan, NY, the nearest location by straight line distance might be across the Hudson River in New Jersey. But actually getting there will require you to drive or walk quite some distance in order to cross a bridge over the river.

It would be much quicker to make your way to a location in Manhattan that might be a bit further by straight-line distance, but doesn’t require you to cross any rivers.

So how can we help our users identify the locations that will take the least amount of time to get to? We can reorder our results by driving time before we present them to our end user. By using the Query API to obtain a set of locations in the vicinity of our user, then using the Routes API to determine how long it will take to drive to each of our nearby locations, we can guide our user to our locations which will be quickest for them to get to.

Reordering Results by Driving Time

The key step here will be the reordering of our results so that they are presented in order of least driving time, and doing this without making separate Routes API requests for each location. We achieve this by constructing a multi-point route request, going from the search origin (our user’s location) to each of the locations in our Query API result set and back. The Routes API supports up to 25 waypoints per route request, so we could use this technique to determine the driving distances for up to 12 locations in a single request. We can use the resulting drive time (or drive distance) of each leg of our route to reorder our locations before presenting them.

Sample Application

Included below is code for a basic application that combines the Bing Maps AJAX Control v7, the Query API, and the REST Locations and Routes APIs, to enable a fully client-side locator scenario in which we present our results based on driving time.

At a high-level, the application will:

  • Capture a user address, and geocode it via the Locations API
  • Take the latitude and longitude from our geocoded location, and use the Query API with a spatial filter to find the nearest 5 Fourth Coffee Shops to the user address
  • Generate one multi-point route request that goes from our geocoded location to each Fourth Coffee Shop and back
  • Reorder our results based on the driving distance from the geocoded location to each Fourth Coffee Shop
  • Present the reordered results to the end user on a map using the Bing Maps AJAX Control v7

To optimize performance, we limit the result set to 5 locations, but to reduce the chances that there are other stores that might be closer by driving time than the 5 that are presented, we could also consider retrieving 10 results from the Query API, reordering them by drive time, then presenting only the top 5 from our reordered result set.

Here is the code. To view and use the code, developers will need to obtain a key and insert that key into the placeholder within the code sample.