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

Dear Monks

I'm using Win32::OLE to work with Excel (and I am happy with it). However I am stuck with the following issue:

A cell I access should contain a date. Therefore I read it using

@val = $WPsheet->Range("A1")->{FormulaR1C1}
which works fine - as long as Excel thinks the cell contains a date. Unfortunately, in some sheets the date is stored as a string - so I should read the {'value'} instead of the {FormulaR1C1} and parse it myself.

What is the best (most robust) way to find out if the date is stored as an "Excel-date" or an "Excel-string"?

Rata

Update: Thanks for your hints, davies and priyaviswam. I decided to go the "value eq value2"-approach for now ... but will keep the format-approach in mind.

@davies When creating my inital code, I somewhere found @val and using the formula-property - and it worked. So there is no reason to keep it other than cargo-cult.

Replies are listed 'Best First'.
Re: Win32::OLE Excel: identify cell-format
by davies (Monsignor) on Nov 16, 2011 at 10:05 UTC

    The technique I usually use is to compare value to value2. I'm a little surprised at you using @val instead of $val, but strange things of which I was not aware appear to be happening with Excel dates.

    use strict; use warnings; use diagnostics; use Win32::OLE; my $xl = Win32::OLE->new('Excel.Application'); $xl->{Visible} = 1; my $wb = $xl->Workbooks->Add(); for (2..$wb->Sheets->{Count}) { $wb->Sheets(2)->Delete; } my $cell = $wb->Sheets(1)->Cells(1,1); $cell->{Value} = '1/1/1'; my $v = $cell->Value; my $v2 = $cell->{Value2}; print "$$v $v2\n"; $cell->{Value} = '\'1/1/1'; $v = $cell->Value; $v2 = $cell->{Value2}; print "$v $v2\n";

    As you will see, when you have a text string, Value and Value2 are the same, but when there is a date, Win32::Ole returns a reference for Value (VBA just returns the value - 01/01/2001 in this case). I don't know if the number held in the reference makes sense to you, but it doesn't to me. However, the important point is that if a cell contains a date, the two will differ. This applies whether the date is entered directly or is calculated via a formula (again, I'm unclear why you use the Formula property).

    Rumour has been heard in the land of other cases where Value and Value2 differ. If they exist, they are very rare. I've certainly never needed to know about them.

    Unless you know for sure that there will be no transatlantic confusion, you may have to watch out for date formats.

    Regards,

    John Davies

Re: Win32::OLE Excel: identify cell-format
by priyaviswam (Sexton) on Nov 16, 2011 at 10:19 UTC
    Check whether the format of the data in a cell is Variant of VT_DATE, if it is "Excel - date" or Variant of VT_R8, if it is "Excel-string"