Format Excel from Access - Cells of object - Global failed

I have code in access that exports an excel spreadsheet and does some formatting.  (see below)

The first time I run the below code the spreadsheet opens I get the top row with auto filters and the rows turn bold that have "Sort - Totals" & "Vendor - Totals" in Column D.  Everything is good.

If I close the spreadsheet - then run the code again - I get an error on the    "For Each c In Range(Range("D1"),. . .   Line (see below)

Run-time error '1004':          Method 'Range' of object'_Global' failed

I can click the Reset button in the Visual Basic Editor - then run my query and it runs correctly.

Any suggestion on how to fix this error?

Thanks for your help


Here is the code:
Private Sub Command8_Click()

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "AP_Aging_Report", "c:\temp\ExcelFormat.xls", True

'========Formating VBA=========

Application.SetOption "Show Status Bar", True

Dim filePath As String
filePath = "c:\temp\ExcelFormat.xls"

Dim xl As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
 
Set xl = New Excel.Application
 
Set xlBook = xl.Workbooks.Open("c:\temp\ExcelFormat.xls")
 
Set xlSheet = xlBook.Worksheets(1)
 
xl.Visible = True
 
With xlSheet
 
.Application.Rows("1:1").Select
.Application.Selection.Font.Bold = True
.Application.Range("A1").Select
.Application.Selection.AutoFilter
.Application.Cells.Select
.Application.Selection.Columns.AutoFit
.Application.Range("A1").Select

For Each c In Range(Range("D1"), Range("D" & Cells.Rows.Count).End(xlUp))  <------(this line is where I get the error)
    If c = "Vendor - Totals" Or c = "Sort - Totals" Then
        c.EntireRow.Font.Bold = True
    End If
Next

End With

End Sub
johnmadiganAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Wayne Taylor (webtubbs)Commented:
You haven't tied in Range or Cells with xlSheet...

    For Each c In .Range(.Range("D1"), .Range("D" & .Cells.Rows.Count).End(xlUp))

Also, try and avoid the use of Select. It's generally unnecessary and will only slow down the execution.

Private Sub Command8_Click()

 DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "AP_Aging_Report", "c:\temp\ExcelFormat.xls", True

 '========Formating VBA=========

 Application.SetOption "Show Status Bar", True

 Dim filePath As String
 filePath = "c:\temp\ExcelFormat.xls"

 Dim xl As Excel.Application
 Dim xlBook As Excel.Workbook
 Dim xlSheet As Excel.Worksheet
  
 Set xl = New Excel.Application
  
 Set xlBook = xl.Workbooks.Open("c:\temp\ExcelFormat.xls")
  
 Set xlSheet = xlBook.Worksheets(1)
  
 xl.Visible = True
  
 With xlSheet
  
 .Application.Rows("1:1").Font.Bold = True
 .Application.Range("A1").AutoFilter
 .Application.Cells.Columns.AutoFit

 For Each c In .Range(.Range("D1"), .Range("D" & .Cells.Rows.Count).End(xlUp))
     If c = "Vendor - Totals" Or c = "Sort - Totals" Then
         c.EntireRow.Font.Bold = True
     End If
 Next

 End With

 End Sub

Open in new window

NorieAnalyst Assistant Commented:
Try this.
Option Explicit

Private Sub Command8_Click()
Dim filePath As String
Dim xl As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "AP_Aging_Report", "c:\temp\ExcelFormat.xls", True

    Application.SetOption "Show Status Bar", True

    '========Formating VBA=========

    filePath = "c:\temp\ExcelFormat.xls"

    Set xl = New Excel.Application

    Set xlBook = xl.Workbooks.Open("c:\temp\ExcelFormat.xls")

    Set xlSheet = xlBook.Worksheets(1)

    xl.Visible = True

    With xlSheet

        .Rows("1:1").Font.Bold = True
        .Range("A1").AutoFilter
        .Cells.Columns.AutoFit

        For Each c In .Range(.Range("D1"), .Range("D" & .Rows.Count).End(xlUp))
            If c = "Vendor - Totals" Or c = "Sort - Totals" Then
                c.EntireRow.Font.Bold = True
            End If
        Next

    End With

End Sub

Open in new window

Wayne Taylor (webtubbs)Commented:
It will probably also have issues with 'xlUp' as that is not an Access constant. Replace it with it's equivalent integer value, -4162.

For Each c In .Range(.Range("D1"), .Range("D" & .Cells.Rows.Count).End(-4162))
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

NorieAnalyst Assistant Commented:
Wayne

It looks like early binding is being used so xlUp shouldn't be a problem.
johnmadiganAuthor Commented:
Thanks for the help - both code examples work great.

I have a question on the auto fit code.  I was told to make columns "I:Q" currency.  So I put in
           .Range("I:Q").Style = "Currency"

This set my values to currency but I noticed that with the $ sign some of the Columns are not wide enough.

I tried to move the  my currency code before  ".Cells.Columns.AutoFit" - but no luck.

Is there any way to get the columns wide enough to see the numbers instead of ####?

Thanks,
NorieAnalyst Assistant Commented:
Moving the autofit after the currency formatting should work, did you try that?
  With xlSheet

        .Rows("1:1").Font.Bold = True
        .Range("A1").AutoFilter
        .Range("I:Q").Style = "Currency"
        .Cells.Columns.AutoFit

Open in new window

johnmadiganAuthor Commented:
Yes I tried that - but it didn't adjust the Columns with currency.

For a work around I used the AutoFit for A-H and then set the I-Q to a column width.

Sure would be nicer if the AutoFilter spread out the currency columns.

Here is my work around.



.Rows("1:1").Font.Bold = True
        .Range("A1").AutoFilter
        .Range("I:Q").Style = "Currency"
        .Columns("A:H").AutoFit
        .Columns("I:Q").ColumnWidth = 15.5
        '.Cells.Columns.AutoFit
NorieAnalyst Assistant Commented:
What happens if you use NumberFormat instead of Style?
.Range("I:Q").NumberFormat = "_-$* #,##0_-;-$* #,##0_-;_-$* "-"_-;_-@_-"
.Columns.AutoFit

Open in new window

johnmadiganAuthor Commented:
I was able to change the docmd from transfer to acOutput and the currency came over from the access query - so it works now.

One last strange thing is the code to freeze the top row.  It runs the first time and freezes the first row OK.  When I run it a second time all the formatting works but the freezing.  If I go and click the reset on the VBA window and run it again - I get the top row to freeze.

Any suggestions?

Below is my code------

 Set xl = New Excel.Application

    Set xlBook = xl.Workbooks.Open("AP_Aging-AECVA.xlsx")

    Set xlSheet = xlBook.Worksheets(1)

    xl.Visible = True

    With xlSheet
     
       
        For Each c In .Range(.Range("D1"), .Range("D" & .Rows.Count).End(xlUp))
            If c = "Vendor - Totals" Or c = "Sort - Totals" Then
                c.EntireRow.Font.Bold = True
            End If
        Next

        .Rows("1:1").Font.Bold = True
        .Range("A1").AutoFilter
        .Cells.Columns.AutoFit
        .Rows("2:2").Select
         ActiveWindow.FreezePanes = True
        .Range("A1").Select
       
    End With
NorieAnalyst Assistant Commented:
The problem is using Select and ActiveWindow.

I think I've got some code somewhere that freezes panes using a different method.

I'll see if I can find it and post it.

Here it is as, add it after the existing code.
    With xl
        .Goto xlSheet.Range("A1"), True
        .Goto xlSheet.Range("A2"), False
        .ActiveWindow.FreezePanes = True
    End With

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
johnmadiganAuthor Commented:
This is working great.

Thanks so much for your help - I learned some good techniques doing this project.

Thanks again
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.