Software solutions and questions blog
RSS icon Email icon Home icon
  • Een recordset snel naar excel exporteren

    Posted on September 24th, 2008 Christophe No comments

    Met visual basic kan je natuurlijk door een ganse recordset loopen en record per record naar excel gaan wegschrijven.
    Gemakkelijker gaat het als je de recordset in één keer, in zijn geheel exporteert naar excel.

    Dim RS As New ADODB.Recordset
    CREATERECORDSETONSERVER RS, dbOCMW ' function to create a recordset on the serverside

    RS.Open "select * from MyQuery where jaar = " & cmbJaar.Text

    'Start a new workbook in Excel
    Dim oApp As New Excel.Application
    Dim oBook As Excel.Workbook
    Dim oSheet As Excel.Worksheet

    Set oBook = oApp.Workbooks.Add
    Set oSheet = oBook.Worksheets(1)

    'Add the field names in row 1
    Dim i As Integer
    Dim iNumCols As Integer

    iNumCols = RS.Fields.Count
    For i = 1 To iNumCols
    oSheet.Cells(1, i).Value = RS.Fields(i - 1).Name
    Next

    'Add the data starting at cell A2
    oSheet.Range("A2").CopyFromRecordset RS

    'Format the header row as bold and autofit the columns
    With oSheet.Range("a1").Resize(1, iNumCols)
    .Font.Bold = True
    .EntireColumn.AutoFit
    End With

    oApp.Visible = True
    oApp.UserControl = True

    'Close the Database and Recordset
    RS.Close

    In a module we have
    Sub CREATERECORDSETONSERVER(rs)
    Set rs = New ADODB.Recordset
    rs.ActiveConnection = db ' is the active connection with the database
    rs.CursorLocation = adUseServer
    rs.CursorType = adOpenStatic
    rs.LockType = adLockReadOnly
    End Sub

    [tags]visual basic, excell, microsoft office[/tags]

    Leave a reply