Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I have been trying to delete the unwanted sheets at the end of my perl code. It is not getting deleted. I searched this site and tried it in the same way. I am not getting any warnings or errors with -w enabled in the command line. Please help. $Excel->{DisplayAlerts} = 0; for($j=1;$j<9;$j++) { $Book->Worksheets("TxPower$j")->Delete; print "Deleting ...\n"; # $worksheet->Delete; }

Replies are listed 'Best First'.
Re: Deleting excel sheet using win32::ole
by lamp (Chaplain) on Sep 17, 2008 at 14:06 UTC
    set the Win32::OLE warn level for debugging. Set the level to '3', which will croak when any error happens.
    Win32::OLE->Option(Warn => 3);
    And also check for last recorded OLE Errors using the following method.
    Win32::OLE->LastError();
Re: Deleting excel sheet using win32::ole
by binf-jw (Monk) on Sep 17, 2008 at 14:13 UTC
    AM, Firstly please but < code> # code in here </code> next time you post a code snippet, It makes it alot easier to read.

    In the past i've had similar problems when deleteing worksheets the best way i've found is to ensure Alerts are turned of every time you try and deleted something.
    Small example here of how you'd add a Book & Sheet, Delete the sheet, then close the workbook:
    #!usr/bin/perl -w use strict; use Win32::OLE qw( HRESULT ); use constant False => 0; use constant True => 1; my $Excel; { # Open Excel $Excel = Win32::OLE->new( 'Excel.Application', sub { $_[0]->Quit; +} ) || die( '[FATAL]: could not open Excel', $! ); $Excel->{Visible} = False; } { my $Book = $Excel->Workbooks->Add; # Add workbook my $Sheet = $Book->Worksheets->Add; # Add worksheet to work boo +k $Excel->{DisplayAlerts} = False; # Don't display alerts $Sheet->Delete(); # Delete sheet $Book->Close( { SaveChanges => False } ); # Close the work book # Excel exits via the deconstructor closure sub { $_[0]->Quit }; liste +d in the open method }
    Your problem could be as simple as calling $Excel->{DisplayAlerts} = False everytime.

    As far as i know catching errors from Ole is tricky. If you see when i load Win32::Ole i also import HRESULT. This method allows you to compare the last error message generated to one you might be expected.eg.
    if( Win32::Ole->LastError == HRESULT(0x800a01a8)){ print "Error\n"; }

    use warnings; or -w Only warns you about coding errors you've made have a look at the perlexwarn for more info. If you're getting an error from Excel or Word then it's external to perl. As you may or maynot be aware the ole module loads the libraries to control the MS office either by DynaLoader or XS, I'm sure on the specifics the point is they're external to perl and therefore it is hard to catch errors.


    Hope that helps
    John