开发者

Invalid variant operation error

开发者 https://www.devze.com 2023-03-25 10:02 出处:网络
May aim is... I have a xls 开发者_运维问答excel 2003 file... In first colums of first sheet, there are five a two b characters...

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);
    
0

精彩评论

暂无评论...
验证码 换一张
取 消