I create a small tablet in Word, and then I need to make a graph based on it. I found how to add a graph, but the code all the time crashes with an error in the position

w := wrd.ActiveDocument.Shapes.AddOLEObject('MSGraph.Chart.8'); 

and the graph is created but not created based on the data in the table. How to do right?

 procedure TForm1.btn2Click(Sender: TObject); var wrd, w, Child: OleVariant; i: Integer; StartRange: Variant; begin wrd:=CoWordApplication.Create; wrd.Visible:=true; wrd.Documents.Add; wrd.ActiveDocument.Tables.Add(wrd.ActiveDocument.Range(0, 0), 5, 2); wrd.Visible := True; For i:=1 to 5 do begin wrd.ActiveDocument.Tables.Item(1).Cell(i,1).Range.Text := i; wrd.ActiveDocument.Tables.Item(1).Cell(i,2).Range.Text := i*i; end; w:=wrd.ActiveDocument.Shapes.AddOLEObject('MSGraph.Chart.8'); Child:=w.DiagramNode.Children.AddNode; for i:=1 to 5 do begin Child.Children.AddNode; end; end; 
  • Are you sure that the error occurs exactly on the specified line? I have an AV on the following - Child:=w.DiagramNode.Children.AddNode; - kami

1 answer 1

Now there is no Delphi + Office bundle at hand, I give the answer from memory and to my old programs.

No, you have the error in the next line, and not where you assume, because the code

  Child:=w.DiagramNode.Children.AddNode; 

refers to a non-existent object. In order to create a chart from the available tabular data, you actually need to select a table (recording macros with subsequent analysis helps a lot) and then apply the InlineShapes.AddOLEObject method to the selection . Something like this:

 for i:=1 to 5 do begin wrd.ActiveDocument.Tables.Item(1).Cell(i,1).Range.Text := i; wrd.ActiveDocument.Tables.Item(1).Cell(i,2).Range.Text := i*i; end; // Тут кончается ваш код wrd.ActiveDocument.Tables.Item(1).Select; // выбираем вашу таблицу wrd.Selection.InlineShapes.AddOLEObject('MSGraph.Chart.8','',FALSE,FALSE); // вставляем диаграмму по данным таблицы. // Я использую только первые 4 параметра, смотрите сами по ссылке выше, какие и сколько вам нужны 

Your table data should have been copied to an MS Graph object. Then you can work with them. For example:

 Doc:=wrd.ActiveDocument; // ну, мне так проще :) Diag:=Doc.InlineShapes.Item(Doc.InlineShapes.Count); // ещё упрощаем доступ, вдруг понадобится доступ к объекту диаграммы в целом Chart:= Diag.OLEFormat.Object; //а теперь только Chart, только хардкор :) Chart.ChartType := 54; // ну, а дальше делаем, что хотим :) Chart.Application.DataSheet.Activate; Chart.Application.DataSheet.Cells.Clear; Chart.ChartArea.Font.Bold := False; Chart.Application.DataSheet.Cells[1, 1].Value :='11'; 

Of course, Doc , Diag and Chart are variables of type OleVariant .

  • It works :) Just why MS Graph, not MS Excel for charts? - Alexey Kozlov
  • @AlexeyKozlov I don’t know - ask the author :) - Viktor Tomilov