6

如何获取所选单元格的总和值或范围stringgrid?请注意,有时这些单元格包含字符串值!

我尝试过GridCoord,但效果不佳,因为有时会有“隐藏列”。

procedure TMainShowForm.StgSelectionChanged(Sender: TObject; ALeft, ATop,
 ARight, ABottom: Integer);
var
i: Integer;
gc: TGridCoord;
sum:double;
begin
  for i := 1 to stg.SelectedCellsCount do
    begin
      gc := stg.SelectedCell[i - 1];
      sum:=sum+stg.floats[(gc.X),(gc.Y)];
    end;
  AdvOfficeStatusBar1.Panels[0].Text:='Sum = '+ formatfloat('#,##0.',sum);
  AdvOfficeStatusBar1.Panels[1].Text:='Count = '+ inttostr(stg.SelectedCellsCount);
end;
4

1 回答 1

8

如何获取 TStringGrid 中选择的浮点值的总和?

对于标准的 Delphi TStringGrid,例如这种方式:

procedure TForm1.Button1Click(Sender: TObject);
var
  Sum: Double;
  Val: Double;
  Col: Integer;
  Row: Integer;
begin
  Sum := 0;
  for Col := StringGrid1.Selection.Left to StringGrid1.Selection.Right do
    for Row := StringGrid1.Selection.Top to StringGrid1.Selection.Bottom do
      if TryStrToFloat(StringGrid1.Cells[Col, Row], Val) then
        Sum := Sum + Val;
  ShowMessage('Sum of the selection is ' + FloatToStr(Sum) + '.');
end;

如何在 TAdvStringGrid 中获取选择(包括不可见单元格)的浮点值的总和?

因此,您很可能正在使用TAdvStringGrid您可以尝试以下尚未测试或优化的代码。到目前为止,我发现,AllFloats无论隐藏的列或行如何,您都可以使用属性将所有网格单元格作为浮点数访问。假设您想在隐藏某列后对连续选择求和,您可以尝试以下代码:

procedure TForm1.Button1Click(Sender: TObject);
var
  Sum: Double;
  Col: Integer;
  Row: Integer;
begin
  Sum := 0;
  for Col := AdvStringGrid1.Selection.Left to AdvStringGrid1.Selection.Right do
    for Row := AdvStringGrid1.Selection.Top to AdvStringGrid1.Selection.Bottom do
      Sum := Sum + AdvStringGrid1.AllFloats[Col, Row];
  ShowMessage('Sum of the selection is ' + FloatToStr(Sum) + '.');
end;
于 2012-10-09T20:25:17.960 回答