Code to autofit Excel hangs

spikepl

Eledittingent Beliped
Local time
Today, 18:50
Joined
Nov 3, 2010
Messages
6,142
I now run Win7/A2010.

Previously, underXP/A2007, the following code executed perfectly without any human interaction (open an excel file, autofit the columns, close it again):

Code:
Public Sub AutofitExcel(varFile As String)
    Dim xlApp As Object
    Set xlApp = CreateObject("Excel.Application")
    With xlApp
        .Visible = False
        .Workbooks.Open varFile
        Dim wkSt As String
        Dim wkBk As Object
        wkSt = .ActiveSheet.Name
        For Each wkBk In .ActiveWorkbook.Worksheets
            On Error Resume Next
            .wkBk.Activate
            .Cells.EntireColumn.AutoFit
        Next wkBk
        .Sheets(wkSt).Select
    End With
    xlApp.ActiveWorkbook.Save CreateBackup:=False
    xlApp.ActiveWorkbook.Close
    xlApp.Quit
    Set xlApp = Nothing
End Sub
But now, the silly things hangs. When I get fed up waiting, I click on the Excel file, and then Excel says :" Do you want to save changes .... ?"

What needs to be changed in the code?
 
Maybe try turning off the display warning message when excel opens usings something like this:

Code:
xlApp.Application.displayalerts = False

But dont forget to turn them back on at the end, possibly after the save step.

Code:
xlApp.Application.displayalerts = True
 
I am up to date with all updates. The other suggestions I'll check tomorrow.
 
This worked:

Code:
  xlApp.ActiveWorkbook.Close savechanges:=True
 

Users who are viewing this thread

Back
Top Bottom