Calc macro print specific sheet

I am trying to print a specific Calc sheet with a BASIC macro. The situation is that I am entering finance information on one sheet, then click a button to process the transaction, which (among other things) copies some data to a separate receipt sheet, and I want to print that receipt. All that I have seen on printing refers to a Print method for the entire document (and not a sheet, for example), with no way to specify the sheet. There are some print options, including which “page number”, but I believe this just refers to which pages to print from the current sheet. The Print method seems to be pretty good at printing the current sheet, so I would think the following would work:

Dim view As Object
view = oDoc.getCurrentController()
view.setActiveSheet(shtReceipt) 
oDoc.Print(Array())
view.setActiveSheet(shtSource)

And it turns out that this does work, but only(!) when I am stepping through the code, and allow the receipt sheet to appear physically on the screen. But when I run the code full-speed, it always just prints the source sheet! It’s almost like Print will print what is visible on the screen, but the setActiveSheet goes by so quickly that the receipt isn’t visible (yet), and it just prints what is currently on the screen.

So what is the solution?

With Format>Print Ranges>Edit you can set the print range for any sheet to None (the default is Entire Sheet). Then printing the entire document will skip printing that sheet. However you also may need to adjust your printer driver. Mine defaults to print only the selected sheet.

Well I stumbled across this page:

http://ooo-forums.apache.org/en/forum/viewtopic.php?t=35043&p=160780

which at one point says, gee, I don’t know what the problem is, but if I put in a Wait command it works fine. So I tried a Wait before my print, and it still didn’t work. Then I tried a Wait after my print as well, and that worked! And then I tried it without the Wait before the print, and it still worked! Go figure… So here is what I have now:

Dim view As Object
view = oDoc.getCurrentController()
view.setActiveSheet(shtReceipt)
oDoc.Print(Array())
Wait 500
view.setActiveSheet(shtSource) 

This makes absolutely no sense to me. Shouldn’t you have to wait before the print to give the sheet time to appear, and then print it? So I’m not real happy about the solution, but it appears to work.

The fact that I have to put in a Wait at all tells me that there is a bug in LibreOffice. If I setActiveSheet, and then execute a print, it should print the active sheet that I just set, should it not?