This is code for exporting query data to excel. This assignment operator
Range.Value := arrData;
causes exception:
project raised exception class EOleSysError 'Bad variable type'
What may be the reason?
Units excel2000, ComObj are included. Thanks in advance.
procedure Tform1.BExcelClick(Sender: TObject);
var
row,col,i,j:integer;
xls, wb, Range: OLEVariant;
arrData: OleVariant;
begin
Query1.Close;
Query1.Open;
row := Query1.RecordCount;
col := Query1.FieldCount;
arrData := VarArrayCreate([1, row, 1, col], varVariant);
i:=1;
while not query1.Eof do begin
for j:=1 to col do
arrData[i,j] := query1.Fields[j-1].Value;
query1.Next;
Inc(i);
end;
//or tried this
{for i:=1 to row do begin
for j:=1 to col do
arrData[i,j] := Query1.Fields[j-1].Value;
Query1.Next;
end;
}
xls := CreateOLEObject('Excel.Application');
wb := xls.Workbooks.Add;
for j:=1 to col do
WB.Worksheets[1].Cells[1,j]:= dbgrid1.Columns[j-1].Title.Caption;
Range := wb.WorkSheets[1].Range[wb.WorkSheets[1].Cells[2, 1], wb.WorkSheets[1].Cells[row+1, col]];
Range.Value := arrData;
xls.Visible := True;
end;
Update: I find out what causes exception: query contains 2 fields- datetime field ("ExpDate") and и calculated field "summa" (quantity*price). Without them data correctly transferred in excel. If I include them in FDQuery exception occurs. Query:
select
g.GoodsName, --goods name
s.qnt, --quantity of sold good
s.Price, -- price
s.rg*s.price as summa, --(exception)
i.ExpDate, --expDate --(exception)
t.temp --store temperature
from goods g,sales s, incomes i, temperatures t
where (s.Doc_id=:Doc_id) and
(s.goods_id= g.goods_id)and
(s.record_id=i.record_id)and
(g.temp_id=t.id)
group by g.goodsname, s.qnt, s.Price, summa, s.ExpDate, t.temp
order by g.GoodsName
How fix it?
Solution:
In for loop I change operator
arrData[i,j] := Query1.Fields[j-1].Value;
with
arrData[i,j] := OleVariant(Query1.Fields[j-1].Value));