|
参见《导出Excel主从表》一文
Private Sub 导出_Click()
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim rs As New ADODB.Recordset
Dim sql As String
Dim i As Long
Dim fname As String
Dim shtname As String
On Error GoTo 导出_Err
fname = GetFolder '打开文件夹并选取文件
shtname = InputBox("请选择表:", "表选择窗体", "Sheet1") '指定导出到的工作表名称
sql = "select * from 联合查询 where 单据ID=" & Me.单据ID
rs.Open sql, CurrentProject.Connection, adOpenKeyset, adLockOptimistic
Set xlApp = CreateObject("Excel.Application") '创建一个Excel实例
xlApp.Application.Visible = True '使Excel可见
Set xlBook = xlApp.Workbooks.Open(fname) '打开Excel工作簿
'导出主表
xlBook.Application.Sheets(shtname).Select '按指定名称选择工作表
xlBook.Application.Range("A1").Value = "单 据 ID"
xlBook.Application.Range("A2").Value = "单据类型"
xlBook.Application.Range("C1").Value = "单据名称"
xlBook.Application.Range("C2").Value = "日 期"
xlBook.Application.Range("B1").Value = Me.单据ID
xlBook.Application.Range("B2").Value = Me.单据类型
xlBook.Application.Range("D1").Value = Me.单据名称
xlBook.Application.Range("D2").Value = Me.日期
'导出子表
xlBook.Application.Cells(3, 1).Value = "记录ID"
xlBook.Application.Cells(3, 2).Value = "单据ID"
xlBook.Application.Cells(3, 3).Value = "物资ID"
xlBook.Application.Cells(3, 4).Value = "物资名称"
xlBook.Application.Cells(3, 5).Value = "规格型号"
xlBook.Application.Cells(3, 6).Value = "计量单位"
xlBook.Application.Cells(3, 7).Value = "数量"
xlBook.Application.Cells(3, 8).Value = "单价"
xlBook.Application.Cells(3, 9).Value = "金额"
For i = 1 To rs.RecordCount
xlBook.Application.Cells(i + 3, 1).Value = rs("记录ID")
xlBook.Application.Cells(i + 3, 2).Value = rs("单据ID")
xlBook.Application.Cells(i + 3, 3).Value = rs("物资ID")
xlBook.Application.Cells(i + 3, 4).Value = rs("物资名称")
xlBook.Application.Cells(i + 3, 5).Value = rs("规格型号")
xlBook.Application.Cells(i + 3, 6).Value = rs("计量单位")
xlBook.Application.Cells(i + 3, 7).Value = rs("数量")
xlBook.Application.Cells(i + 3, 8).Value = rs("单价")
xlBook.Application.Cells(i + 3, 9).Value = rs("金额")
rs.MoveNext
Next
xlApp.Quit
rs.Close
Set xlApp = Nothing
Set xlBook = Nothing
导出_Exit:
Exit Sub
导出_Err:
MsgBox "数据错误,请检查!"
Resume 导出_Exit
End Sub |
|