如何获取所选单元格的总和值或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;
解决方法
如何在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;