Advertisement
Guest User

Untitled

a guest
May 26th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. Private Sub btnExportSR_Click()
  2. 1 Dim db As DAO.Database
  3. 2 Dim rs As DAO.Recordset
  4. 3 Dim oApp As Excel.Application
  5. 4 Dim i As Integer
  6. 5 Dim oWbk As Object
  7. 6 Dim oWbs As Object
  8.  
  9. 7 Set db = CurrentDb()
  10.  
  11. 8 Set rs = db.OpenRecordset("tblExample")
  12.  
  13. 9 Set oApp = CreateObject("Excel.Application") 'Point to the Excel application
  14. 10 Set oWbk = oApp.Workbooks.Add 'Adds a workbook to select
  15. 11 Set oWbs = oWbk.Worksheets("Blad1") 'Selects the worksheet, would be 'Sheet1' in English
  16. 12 oWbs.Name = "SheetName" 'Changes the name of the currently selected sheet
  17. 13 With oApp
  18. 14 .Visible = True
  19. 15 ' .Workbooks.Add 'Creates a new workbook
  20. 16 .Sheets("SheetName").Select 'Selects the renamed worksheets
  21. 17 .ActiveSheet.Range("A2").CopyFromRecordset rs 'Start copying data from A2 onward, A1 is reserved for the table headers
  22.  
  23. 18 For i = 1 To rs.Fields.Count 'loop through the recordset
  24. 19 .ActiveSheet.Cells(1, i).value = rs.Fields(i - 1).Name 'Make sure the recordset doesn't loop infinitely
  25.  
  26. 'top decoration
  27. 20 .Cells(1, i).FormulaR1C1 = rs.Fields(i - 1).Name 'standard formula used to determine the range used
  28. 21 .Cells(1, i).Font.Bold = True 'headers must be bold (styling choice)
  29. 22 .Cells(1, i).Font.Color = RGB(250, 250, 250) '#FFFFFF / White
  30. 23 .Range("A1:C1").Interior.Color = RGB(150, 150, 150) 'Colour of the header (assumes the amount of headers used is 3, change at your own discretion)
  31. 24 .Range("A1:C1").AutoFilter 1, "<>" 'makes the headers filtered
  32.  
  33. 25 Next i
  34.  
  35. 26 oApp.Cells.EntireColumn.AutoFit 'automatically resizes the sheet for aestatics
  36. 27 oApp.Cells.EntireRow.AutoFit
  37.  
  38. 28 End With
  39.  
  40. 29 rs.Close 'Close the recordset and empty it
  41. 30 Set rs = Nothing
  42.  
  43. 31 db.Close 'Close the database connection
  44.  
  45. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement