|
- '---------------------------------------------------------------------------------------
- ' Procedure : QueryToExcel
- ' DateTime : 2008-12-2 00:02
- ' Author : Henry D. Sy
- ' Purpose : QueryToExcel "查询名称", "工作簿名称", "工作表名称"
- ' xls文件要与Access文件放在同一个文件夹
- '---------------------------------------------------------------------------------------
- '
- Sub QueryToExcel(ByVal strQueryName As String, ByVal XlName As String, ByVal _
- XlShtName As String)
- ' Send the Query results to Excel
- ' for further analysis
- Dim rs As New ADODB.Recordset
- Dim XlApp As New Excel.Application
- Dim XlWb As Excel.Workbook
- Dim fld As ADODB.Field
- Dim intCol As Integer
- Dim intRow As Integer
- ' Get the desired data into a recordset
- On Error GoTo QueryToExcel_Error
- rs.Open strQueryName, CurrentProject.Connection
- ' Open a worksheet
- Set XlWb = XlApp.Workbooks.Open(CurrentProject.Path & "" & XlName & _
- ".xls")
- XlWb.Worksheets(XlShtName).Activate
- ' Copy the data
- ' First the field names
- For intCol = 0 To rs.Fields.Count - 1
- Set fld = rs.Fields(intCol)
- XlWb.Worksheets(XlShtName).Cells(1, intCol + 1) = fld.Name
- Next intCol
- ' Now the actual data
- intRow = 2
- Do Until rs.EOF
- For intCol = 0 To rs.Fields.Count - 1
- XlWb.Worksheets(XlShtName).Cells(intRow, intCol + 1) = _
- rs.Fields(intCol).Value
- Next intCol
- rs.MoveNext
- intRow = intRow + 1
- Loop
- ' Make the worksheet visible
- XlApp.Visible = True
- rs.Close
- Set rs = Nothing
- On Error GoTo 0
- Exit Sub
- QueryToExcel_Error:
- MsgBox "Error " & Err.Number & " (" & Err.Description & ")"
- End Sub
复制代码 |
|