Hugo Bassas
Hugo Bassas

Reputation: 19

Random VBA errors

I'm running a program that saves an excel file, generates a new workbook and then saves it and prints it out. The code runs pretty smoothly, but for some reason I'm having random errors come up. When I say random, I mean VBA stops my program from running, asks me if it wants to debug, and, when I debug, it highlights the line that needs to be corrected.

This is normal behavior, but the line usually won't proceed until the line has been fixed or changed. However, without changing anything in my code and pressing the "play" button straight away, my code works fine again.

This occurs twice: once at the end of a with command:

With newbook
    .Title = newName
    .Worksheets("Sheet1").Name = "MAIN SHEET"
    .Worksheets("Sheet2").Name = "FORMULA SHEET"
    .SaveAs (newName)
End With

And then it occurs with the line:

ActiveSheet.PrintOut

Both of these lines work fine without changing anything and just pressing play.

Is there any way to make these stops in the code not appear?

Thanks for any help!

Upvotes: 0

Views: 373

Answers (1)

Will BeDeleted
Will BeDeleted

Reputation: 87

I suppose it's possible the workbook is not fully formed at the time you're tryingto print/save.

Try introducing a delay before the print/save, something like:

.Worksheets("Sheet2").Name = "FORMULA SHEET"

DoEvents

Sleep 500

DoEvents

.SaveAs (newName)

Upvotes: 1

Related Questions