简体   繁体   中英

MS Access, VBA - Export Crosstable to Excel

OBJECTIVE

  1. Create crosstable from existing table
  2. Export formatted crosstable into excel via VBA

APPROACH

  1. Created query that pulled necessary data for table
  2. Created a crosstable query to properly format data in existing table
  3. !HELP NEEDED! Push crosstable query to excel

ISSUES

  1. I've looked around online and it appears that export a crosstable to excel is difficult - it appears that most forums recommend iterating line-by-line to export the crosstable (this is very surprising). Is there any way I can leverage a method (eg DoCmd.TransferSpreadsheet ) to export a crosstable?

Why this is so difficult amazes me, apologies for the naivety

I simply create the query I want in MS Access.

Then in excel i have a macro I have written that runs the query and outputs to sheet. see below for an example.

Dim cnString As String
Dim rs As New ADODB.Recordset

'Change connection string to an MS Access one
cnString = "Provider=xx;Server=xx,49168;Database=xx;"
rs.Open queryName, cnString, adOpenStatic, adLockOptimistic

'Output Headings
For i = 1 To rs.Fields.Count
        Sheets(PasteSheet).Range(pasteCell).Offset(0, i - 1) = rs.Fields(i - 1).Name
Next i

'Output data
Sheets(PasteSheet).Range(pasteCell).Offset(1, 0).CopyFromRecordset rs
rs.close

If you wanted to do all of this in MS Access then it wouldn't take much to modify. You would simply just need to create a new workbook and then do a very similar thing to the above code.

Following up from my original post. It appears that you can use DoCmd.TransferSpreadsheet to export a crosstable.

I've defined the working code below:

outputQuery = [your cross table query]
outputPath = [save-to file location]
outputFileName = [save-to file name]

DoCmd.TransferSpreadsheet acExport, SpreadsheetType:=acSpreadsheetTypeExcel12Xml, TableName:=outputQuery, FileName:=outputPath & outputfilename

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM