delphi – stringgrid中所选单元格的总和值

前端之家收集整理的这篇文章主要介绍了delphi – stringgrid中所选单元格的总和值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何获取所选单元格的总和值或stringgrid中的范围?请注意,有时这些单元格包含字符串值!

我尝试使用GridCoord,但它不能正常工作,因为有时候会有“隐藏列”.

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

解决方法

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

对于标准的Delphi TStringGrid,例如:

  1. procedure TForm1.Button1Click(Sender: TObject);
  2. var
  3. Sum: Double;
  4. Val: Double;
  5. Col: Integer;
  6. Row: Integer;
  7. begin
  8. Sum := 0;
  9. for Col := StringGrid1.Selection.Left to StringGrid1.Selection.Right do
  10. for Row := StringGrid1.Selection.Top to StringGrid1.Selection.Bottom do
  11. if TryStrToFloat(StringGrid1.Cells[Col,Row],Val) then
  12. Sum := Sum + Val;
  13. ShowMessage('Sum of the selection is ' + FloatToStr(Sum) + '.');
  14. end;

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

因此,您最有可能使用TAdvStringGrid,您可以尝试以下尚未测试或优化的代码.到目前为止,我发现,您可以使用AllFloats属性以浮动方式访问所有网格单元格而不管隐藏的列或行.假设您想在隐藏某个列后对连续选择求和,您可以尝试以下代码

  1. procedure TForm1.Button1Click(Sender: TObject);
  2. var
  3. Sum: Double;
  4. Col: Integer;
  5. Row: Integer;
  6. begin
  7. Sum := 0;
  8. for Col := AdvStringGrid1.Selection.Left to AdvStringGrid1.Selection.Right do
  9. for Row := AdvStringGrid1.Selection.Top to AdvStringGrid1.Selection.Bottom do
  10. Sum := Sum + AdvStringGrid1.AllFloats[Col,Row];
  11. ShowMessage('Sum of the selection is ' + FloatToStr(Sum) + '.');
  12. end;

猜你在找的Delphi相关文章