当通过OLE从我的Delphi程序自动化Excel和尝试一个单元格的NumberFormat属性设置为“一般”,并编写公式,Excel是提高例外与此通知:如何使用Delphi正确设置公式的Excel NumberFormat属性?
项目X.exe引发的异常类EVariantInvalidOpError与消息'变体操作无效'。
换句话说我的问题是: 哪个NumberFormat是包含文本函数(如concatenate)的公式单元格的最佳格式?
这里是我的示例代码:
USE System.Win.ComObj;
procedure TForm1.Btn_1Click(Sender: TObject);
var
XL: variant;
Sheet,
WorkBook: variant;
begin
try
XL := GetActiveOleObject('Excel.Application');
except
XL := CreateOleObject('Excel.Application');
end;
XL.Visible := False;
WorkBook:=XL.WorkBooks.Add;
Sheet:=XL.WorkBooks[1].WorkSheets.Add;
Sheet.Name := 'Test-Sheet';
Sheet.Cells[1, 1]:='col1';
Sheet.Cells[1, 1].Font.Bold := True;
Sheet.Cells[1, 1].Font.Size := 10;
Sheet.Cells[1, 2]:='col2';
Sheet.Cells[1, 2].Font.Bold := True;
Sheet.Cells[1, 2].Font.Size := 10;
Sheet.Cells[1, 3]:='Basic Formula';
Sheet.Cells[1, 3].Font.Bold := True;
Sheet.Cells[1, 3].Font.Size := 10;
Sheet.Cells[1, 3].numberformat := 'General';
Sheet.Cells[1, 4]:='Text function ';
Sheet.Cells[1, 4].Font.Bold := True;
Sheet.Cells[1, 4].Font.Size := 10;
Sheet.Cells[1, 4].numberformat := 'General';
Sheet.Cells[2, 1].Value := '1000';
Sheet.Cells[2, 2].Value := '500'; // or := 'abcxyz' for concat
Sheet.Cells[2, 3].Value := '=A2+B2'; //this one is ok
Sheet.Cells[2, 4].Value := '=CONCATENATE(A2;B2)'; //this one raised exception...
XL.WorkBooks[XL.WorkBooks.Count].SaveAs( ExtractFileDir(Application.ExeName) +'\Test.xls' ,51);
XL.ActiveWorkbook.Close(0);
XL.Quit;
end;
你试过':'而不是';'或''= A2&B2''? – pnuts
@pnuts:不,我没有尝试过,但你说的方式正常工作... 非常感谢你... – AliDehban