简体   繁体   中英

Invalid variant operation error

May aim is... I have a xls excel 2003 file... In first colums of first sheet, there are five a two b characters...

With my delphi code, I want to output such that.. This file has 5 a characters, two b characters..... When I compile and run the program, it gives Invalid variant operation ... annoying... The complete code is given below:

unit Unit1;

interface

uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComObj, StdCtrls;

type
  TForm1 = class(TForm)
    Label1: TLabel;
    procedure FormCreate(Sender: TObject);
  private { Private declarations }
  public { Public declarations }

  end;

var
  Form1: TForm1;

var
  uygulama: variant;

var
  i, w: integer; 
 // var str:string; 

implementation

{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
  uygulama := CreateOleObject('Excel.Application');
  uygulama.visible := false;
  uygulama.Workbooks.open['c:\liste.xls'];

  // label1.Caption:=(uygulama.ActiveSheet.cells[1,1]);

  i := 1;
  w := 1;
  repeat
    if uygulama.ActiveSheet.cells[i, 1] = 'a' then
      inc(w);
  until uygulama.ActiveSheet.cells[i, 1] = '';

  Label1.Caption := inttostr(w);

end;

end.  

To access a value from a cell you must use the value property

try this

  repeat
    if uygulama.ActiveSheet.cells[i, 1].value = 'a' then
      inc(w);
  until uygulama.ActiveSheet.cells[i, 1].value = '';

Assuming that you have now figured out how to get the value of the cell, there are a few points regarding your code which I wish to make.

  1. The repeat loop is going to be very slow. It would be better to store the cell's value in a local variable before entering the loop and then perform your counting operation on your local variable.

  2. The loop stands a very good chance of being infinite because you're not changing any values which change (apart from w). Why not write something like

     s:= uygulama.activesheet.cells[i,1].value; w:= 0; for i:= 1 to length (s) do if s[i] = 'a' then inc (w); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM