views:

627

answers:

2

We have just updated an application which uses the Excel type library to Delphi 2009 from Delphi 2006. What I am finding is that nearly nothing now works - nearly any call to Excel results in a message "Bad variable type.". For example we may do: Sheet.Cells.Item[Row, Column].Value := Value where Sheet is an ExcelWorksheet and Value is a Variant. The next thing we see in the stack is a call to _DispInvoke in Variants, and then on into ComObj. What am I doing wrong?

+2  A: 

I can advise you to recreate/reimport the type library if either the Excel or the Delphi version has changed. Using a TLB from another versions often gives these problems.

Gamecat
We were previously using the Office XP sample imports that come with Delphi 2006 and 2009, and this seemed to work fine (for how we were using it) for Excel 2000 - 2007. Anyway, I have now imported the type library afresh and get the exact same problem.
Andrew
+2  A: 

It turned out that we had a generic procedure to set value of a cell of the form:

procedure SetValue(aSheet: ExcelWorksheet; aRow, aCol: Integer; aValue: Variant)
begin
  aSheet.Cells.Item[aRow, aCol].Value := aValue;
end;

this fails with the error I mentioned. If I change this to:

procedure SetValue(aSheet: ExcelWorksheet; aRow, aCol: Integer; aValue: Variant)
var
  sValue: WideString;
begin
  sValue:= aValue;
  aSheet.Cells.Item[aRow, aCol].Value := sValue;
end;

To me this suggests that Delphi 2009 is doing something different with variants (than D2006 was at least), something that COM doesn't like, unless someone has a better explanation? Anyway I'm happy to muddle on with this workaround for the time being.

Andrew
What type was the value in your variant? Looks like this will create a new variant of type string, which COM needs. Perhaps your old code was passing an ANSIString which the COM variant doesn't support?
mj2008