2
votes

I'm using Delphi XE3 and I'm developing an application to read numerical type cells from Excel. I'm using TStringGrid for this import.

I already know, how to get them to the string grid, but can't manage to do any mathmatical functions like in Excel. How do I calculate min, max and average values for selected cell values of my string grid ?

1
You can use Live Bindings to do this. Or JEDI's expression evaluator. Both of these libraries have ample demos and samples available.David Heffernan

1 Answers

2
votes

You can try the following function. It returns the count of numeric values found in the current string grid's selection. To declared parameters passed to it returns minimum, maximum and average values from the current selection's numeric values (if there are some):

uses
  Math;

function CalcStats(AStringGrid: TStringGrid; var AMinValue, AMaxValue,
  AAvgValue: Double): Integer;
var
  Col, Row, Count: Integer;
  Value, MinValue, MaxValue, AvgValue: Double;
begin
  Count := 0;
  MinValue := MaxDouble;
  MaxValue := MinDouble;
  AvgValue := 0;

  for Col := AStringGrid.Selection.Left to AStringGrid.Selection.Right do
    for Row := AStringGrid.Selection.Top to AStringGrid.Selection.Bottom do
    begin
      if TryStrToFloat(AStringGrid.Cells[Col, Row], Value) then
      begin
        Inc(Count);
        if Value < MinValue then
          MinValue := Value;
        if Value > MaxValue then
          MaxValue := Value;
        AvgValue := AvgValue + Value;
      end;
    end;

  Result := Count;
  if Count > 0 then
  begin
    AMinValue := MinValue;
    AMaxValue := MaxValue;
    AAvgValue := AvgValue / Count;
  end;
end;

Here's a sample usage:

procedure TForm1.Button1Click(Sender: TObject);
var
  MinValue, MaxValue, AvgValue: Double;
begin
  if CalcStats(StringGrid1, MinValue, MaxValue, AvgValue) > 0 then
    Label1.Caption :=
      'Min. value: ' + FloatToStr(MinValue) + sLineBreak +
      'Max. value: ' + FloatToStr(MaxValue) + sLineBreak +
      'Avg. value: ' + FloatToStr(AvgValue)
  else
    Label1.Caption := 'There is no numeric value in current selection...';
end;

Another chapter is how to get notification when the selection of a string grid changes. There's no event nor virtual method for implementing event like OnSelectionChange. But that would be topic for another question.