简体   繁体   English

MS Access,VBA-将交叉表导出到Excel

[英]MS Access, VBA - Export Crosstable to Excel

OBJECTIVE 目的

  1. Create crosstable from existing table 从现有表创建交叉表
  2. Export formatted crosstable into excel via VBA 通过VBA将格式化的交叉表导出到excel

APPROACH 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 将交叉表查询推送到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). 我在线上四处查看,似乎很难将交叉表导出为ex​​cel-似乎大多数论坛建议逐行迭代以导出交叉表(这非常令人惊讶)。 Is there any way I can leverage a method (eg DoCmd.TransferSpreadsheet ) to export a crosstable? 有什么办法可以利用一种方法(例如DoCmd.TransferSpreadsheet )来导出交叉表?

Why this is so difficult amazes me, apologies for the naivety 为什么这么难,令我惊讶,为天真致歉

I simply create the query I want in MS Access. 我只是在MS Access中创建所需的查询。

Then in excel i have a macro I have written that runs the query and outputs to sheet. 然后在Excel中,我编写了一个宏,用于运行查询并将其输出到工作表。 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. 如果您想在MS Access中完成所有这些操作,则无需花费太多修改。 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. 看来您可以使用DoCmd.TransferSpreadsheet导出交叉表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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