SyntaxHighlighter

2013-11-12

AccessからExcelに出力

参考資料:Export from ACCESS to Excel using VBA

AccessからVBAでExcelに出力は次のようなコードで実行できる。
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "tbl_lookup_ird", "c:\temp.xls", True


似ている方法で、Excelオブジェクトを作成してからそこに出力を書き込む方法もある。
Public Sub QueryToExcel(ExcelFile As String)
Dim db As Database
Dim qdf As QueryDef

Dim qryCount As Integer
Dim SheetName As String

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.Add
    Set xlSheet = xlBook.Worksheets(1)

    'Make the worksheet visible.
    xlSheet.Application.Visible = True

    Set db = CurrentDb()

    With db
        qryCount = 0
        For Each qdf In .QueryDefs
            qryCount = qryCount + 1
            ' Output qryCount, .Name and .SQL to the next line
            ' in a sheet in the Excel file
            With xlSheet.Cells(qryCount, 1)
                .Value = Str(qryCount)
                .Font.Size = 12
                .Font.Bold = True
            End With
            With xlSheet.Cells(qryCount, 2)
                .Value = qdf.Name
                .Font.Size = 12
                .Font.Bold = True
            End With
            With xlSheet.Cells(qryCount, 3)
                .Value = qdf.SQL
                .Font.Size = 10
            End With
        Next qdf
    End With

    'Save the new worksheet, close Excel and clear the object variable.
    xlSheet.SaveAs ExcelFile
    xlSheet.Application.Quit
    Set xlSheet = Nothing

    ' Create new sheets in the newly created Excel file for
    ' the results of each of the queries
    With db
        qryCount = 0
        For Each qdf In .QueryDefs
            With qdf
                qryCount = qryCount + 1
                SheetName = "Query" & Trim(Str(qryCount))

                ' Create a new sheet in the specified Excel file with
                ' the output of the named query.
                ' If there is a pre-existing one with the same name
                ' the new sheet will have a "1" appended to its name.

                ' Problems or issues:
                ' 1. Invalid queries will error out
                ' 2. Action queries will error out
                ' 3. Queries with parameters will require user input

                DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
                    .Name, ExcelFile, , SheetName
            End With
        Next qdf
        .Close
    End With

End Sub


あるいは次のように
Dim appExcel As Excel.Application
    Dim wbk As Excel.Workbook
    Dim wks As Excel.Worksheet
    Dim rng As Excel.Range
    
    Dim fileName As String

    Set appExcel = Excel.Application
    appExcel.Visible = True
    Set wbk = appExcel.Workbooks.Add
    Set wks = wbk.Worksheets(1)
    Set rng = wks.Range("A2:I4001")
    wks.Cells(1, 1).Value = "Generating data..."
    
    Set rst = CurrentDb.OpenRecordset(customQuery)
    If (rst.RecordCount > 0) Then
        cnt = 1
        For Each fld In rst.Fields
            wks.Cells(1, cnt).Value = fld.Name
            cnt = cnt + 1
        Next fld
        Call rng.CopyFromRecordset(rst, 4000, 26)
    End If
    
    fileName = ExportDir & "\Molenproductie" & DateTimeFrom & "-" & DateTimeTo & ".xls"
    wks.SaveAs (fileName)
    
    rst.Close
    Set rst = Nothing


ところで、AccessからExcelに出力してからPivot Tableを作成するという手法がある。
但し、次のコードはExcelから直接にAccessのデータベースへ接続してデータを取り出しているようです。

Sub DAOCopyFromRecordSet(DBFullName As String, TableName As String, _
    FieldName As String, TargetRange As Range)
' Example: DAOCopyFromRecordSet "C:\FolderName\DataBaseName.mdb", _
    "TableName", "FieldName", Range("C1")
Dim db As Database, rs As Recordset
Dim intColIndex As Integer
    Set TargetRange = TargetRange.Cells(1, 1)
    Set db = OpenDatabase(DBFullName)
    Set rs = db.OpenRecordset(TableName, dbOpenTable) ' all records
    'Set rs = db.OpenRecordset("SELECT * FROM " & TableName & _
        " WHERE " & FieldName & _
        " = 'MyCriteria'", dbReadOnly) ' filter records
    ' write field names
    For intColIndex = 0 To rs.Fields.Count - 1
        TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
    Next
    ' write recordset
    TargetRange.Offset(1, 0).CopyFromRecordset rs
    Set rs = Nothing
    db.Close
    Set db = Nothing
End Sub




0 件のコメント:

人気の投稿