2

我正在使用 Delphi XE3,并且正在开发一个应用程序来从 Excel 中读取数字类型的单元格。我正在使用TStringGrid此导入。

我已经知道,如何让它们进入字符串网格,但无法像 Excel 中那样执行任何数学函数。如何计算字符串网格的选定单元格值的最小值、最大值和平均值?

4

1 回答 1

2

您可以尝试以下功能。它返回在当前字符串网格的选择中找到的数值的计数。传递给它的声明参数返回当前选择的数值(如果有的话)的最小值、最大值和平均值:

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;

这是一个示例用法:

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;

另一章是如何在字符串网格的选择发生变化时获得通知。没有事件也没有虚拟方法来实现像OnSelectionChange. 但这将是另一个问题的主题。

于 2013-01-21T23:30:29.983 回答