Wednesday, February 27, 2019

Export SQL query results to Excel report

Private Sub cmdExportToExcel_Click()
   Dim lI As Long
   Dim rsData As New adodb.Recordset
   Dim sSql As String
   
   
'   Dim xlApp As New Excel.Application
'   Dim xlWorkbook As Excel.Workbook
'   Dim xlSheet As Excel.Worksheet
   
   Dim xlApp As Object
   Set xlApp = CreateObject("Excel.Application")
   Dim xlWorkbook As Object
   Dim xlSheet As Object
   
   
   cmdExportToExcel.Enabled = False
   xlApp.Visible = True
   sSql = txtQuery.Text
   rsData.Open sSql, cnConnect, adOpenStatic
   If rsData.EOF = False Then
      'Data was retured from query
      Set xlWorkbook = xlApp.Workbooks.Add
      Set xlSheet = xlWorkbook.Sheets.Add
      xlSheet.Name = "Report"
      
      For lI = xlWorkbook.Worksheets.Count To 1 Step -1
         If xlWorkbook.Worksheets(lI).Name <> "Report" Then
            'Remove any sheets created by default (Sheet1, Sheet2, Sheet3, etc)
            xlWorkbook.Worksheets(lI).Delete
         End If
      Next lI
      
      xlSheet.Range("A4").CopyFromRecordset rsData
      'Copy the recordset to Excel
      
      For lI = 0 To rsData.Fields.Count - 1
         xlSheet.Cells(3, lI + 1).Value = rsData.Fields(lI).Name
         'Put the name of each colum on the top row
      Next lI
      
      xlSheet.Rows(3).EntireRow.Font.Bold = True
      'Make header row bold
      
      xlSheet.Columns.Font.Name = "Verdana"
      xlSheet.Columns.Font.Size = 12
      
      xlSheet.Range("A1").Value = Now
      'Put the date and time in the upper left corner

      xlSheet.Activate
      If xlSheet.Application.WindowState <> Excel.XlWindowState.xlNormal Then
         'Cells cannot be merged when the window is minimized, so don't let it be minimized
         xlSheet.Application.WindowState = Excel.XlWindowState.xlNormal
      End If
      
      xlSheet.Range(xlSheet.Cells(2, 1), xlSheet.Cells(2, rsData.Fields.Count)).Merge
      'Combine the report name cells for centering
      xlSheet.Range("A2").Value = "Report Name"
      xlSheet.Range("A2").HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
      xlSheet.Range("A2").EntireRow.Font.Bold = True
      
      xlSheet.UsedRange.Columns.AutoFit
      'Expand all cells to the size of the data
      xlSheet.Rows(1).Show
      'Move to the top of the sheet
      xlSheet.Rows(1).Select
      'Set up spreadsheet to freeze header row
      xlApp.ActiveWindow.SplitColumn = 0
      xlApp.ActiveWindow.SplitRow = 3
      'Freeze header row so it remains visible when scrolling data
      xlApp.ActiveWindow.FreezePanes = True
   
      xlSheet.PageSetup.PrintTitleRows = "$1:$4"
      'Keep the header rows visible when printing
      xlSheet.PageSetup.Zoom = False
      xlSheet.PageSetup.FitToPagesTall = False
      xlSheet.PageSetup.FitToPagesWide = 1
      'Scale the printout so all the columns can be seen
   End If
   rsData.Close
   
   cmdExportToExcel.Enabled = True
End Sub

No comments:

Post a Comment