We help IT Professionals succeed at work.

Access VBA Excel bold not working

Murray Brown
Murray Brown used Ask the Experts™
on
Hi
In the following Access VBA code the only line that doesn't work is
Worksheet.Selection.Font.Bold = True


Public Function ExcelExportAndFormat(ByVal CRecordset As DAO.Recordset, ByVal CSheetName As String) As Object

  On Local Error Resume Next

  Dim Excel As Object ' Excel.Application
  Dim Workbook As Object ' Excel.Workbook
  Dim Worksheet As Object ' Excel.Worksheet
 
  Dim Count As Long
 
  Set ExcelExportAndFormat = Nothing
  Set Excel = CreateObject("Excel.Application")
  Set Workbook = Excel.Workbooks.Add
  Set Worksheet = Workbook.Sheets(1)
  Worksheet.Name = CSheetName
  For Count = 0 To CRecordset.Fields.Count - 1
    Worksheet.Range("A1").Offset(, Count).value = CStr(CRecordset.Fields(Count).Name)
  Next Count
 
  Worksheet.Range("A2").CopyFromRecordset CRecordset
  Worksheet.Cells.EntireColumn.AutoFit
  Worksheet.Rows("1:1").Select
  Worksheet.Selection.Font.Bold = True
 
  Set ExcelExportAndFormat = Worksheet
  Excel.Visible = True
  Set Worksheet = Nothing
  Set Workbook = Nothing
  Set Excel = Nothing

End Function
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Production Manager
Commented:
Worksheet.Rows(1).Font.Bold = True

Open in new window

That should do it. No need to select.
Daniel PineaultPresident / Owner CARDA Consultants Inc.
Distinguished Expert 2018
Commented:
Access knows nothing of Select, Selection...

You should avoid using variable named after Excel reserved words (Workbook, WorkSheet, ...) as if ever you use Early binding you are going to have major code changes to do.  Better code it properly now and have that flexibility should you need it.  You can look at https://www.devhut.net/2017/03/15/ms-access-vba-export-recordset-to-excel/ just as a reference to give you an idea of variable naming, ...
Murray BrownASP.net/VBA/VSTO Developer

Author

Commented:
Great. Thanks very much