如何将表单中的所有记录导出到 Excel 工作表
How do I export all records from a form to an Excel worksheet
编辑:没关系,我找到了一种方法。我将 post 我的回答作为一个单独的 post。
我有一个包含多条记录的连续表格。我希望能够将表单上的所有记录信息导出到名为 "RawData" 的 Excel worksheet 中,其中 Excel 文件位于某个静态位置。
我试过 Docmd.OutputTo,但是用包含表单记录的单个 sheet 替换了所有内容,并且 Docmd.TransferSpreadsheet 似乎只在单元格中导入文本 "F1" A1(不知道为什么)。也许我用错了?
您基本上必须打开 Excel 并逐一填写每个单元格。或者这是我至少知道怎么做的唯一方法......原始代码来自 here,但我已经修改了它,因为原始代码只导出一条记录。
Private Sub btnExportExcel_Click()
Dim appExcel As Object
Dim wkbWorkBook As Object
Dim wksSheet As Object
' creates Excel application
Set appExcel = CreateObject("Excel.Application")
' opens workbook for output
Set wkbWorkBook = appExcel.Workbooks.Open("C:\Users\mikec\Desktop\Book1.xlsx")
' get reference to sheet for output
Set wksSheet = wkbWorkBook.Worksheets("RawData")
' for each record, output all fields in the record
Dim rs As Recordset
Dim row As Integer: row = 1
Dim col As Integer: col = 1
Set rs = Me.Form.Recordset
If rs.RecordCount > 0 Then
rs.MoveFirst
Do While Not rs.EOF
Dim fld As Field
For Each fld In Me.Recordset.Fields
wksSheet.Cells(row, col) = fld
col = col + 1
Next fld
rs.MoveNext
col = 1
row = row + 1
Loop
End If
' save and quit
wkbWorkBook.Save
appExcel.Quit
Set wksSheet = Nothing
Set wkbWorkBook = Nothing
Set appExcel = Nothing
End Sub
编辑:没关系,我找到了一种方法。我将 post 我的回答作为一个单独的 post。
我有一个包含多条记录的连续表格。我希望能够将表单上的所有记录信息导出到名为 "RawData" 的 Excel worksheet 中,其中 Excel 文件位于某个静态位置。
我试过 Docmd.OutputTo,但是用包含表单记录的单个 sheet 替换了所有内容,并且 Docmd.TransferSpreadsheet 似乎只在单元格中导入文本 "F1" A1(不知道为什么)。也许我用错了?
您基本上必须打开 Excel 并逐一填写每个单元格。或者这是我至少知道怎么做的唯一方法......原始代码来自 here,但我已经修改了它,因为原始代码只导出一条记录。
Private Sub btnExportExcel_Click()
Dim appExcel As Object
Dim wkbWorkBook As Object
Dim wksSheet As Object
' creates Excel application
Set appExcel = CreateObject("Excel.Application")
' opens workbook for output
Set wkbWorkBook = appExcel.Workbooks.Open("C:\Users\mikec\Desktop\Book1.xlsx")
' get reference to sheet for output
Set wksSheet = wkbWorkBook.Worksheets("RawData")
' for each record, output all fields in the record
Dim rs As Recordset
Dim row As Integer: row = 1
Dim col As Integer: col = 1
Set rs = Me.Form.Recordset
If rs.RecordCount > 0 Then
rs.MoveFirst
Do While Not rs.EOF
Dim fld As Field
For Each fld In Me.Recordset.Fields
wksSheet.Cells(row, col) = fld
col = col + 1
Next fld
rs.MoveNext
col = 1
row = row + 1
Loop
End If
' save and quit
wkbWorkBook.Save
appExcel.Quit
Set wksSheet = Nothing
Set wkbWorkBook = Nothing
Set appExcel = Nothing
End Sub