I have a graph in Excel that I need to move to a specific cell.

In theory, the code should be something like this:

procedure TMyExcelClass.MyProcedure; var sheet, chartObject: Variant; begin sheet := fExcel.ActiveWorkBook.Sheets['какой-то лист']; chartObject := sheet.ChartObjects[1]; chartObject.Left := <левая граница ячейки "F"> chartObject.Top := <верхняя граница ячейки "34"> end; 

How to position the graph to the borders of the cell? (taking into account the fact that the cells can have different width and height)

  • 34 * (cell width + cell frame width). Also with height. - slippyk
  • @slippyk is incorrect. Cells can have different widths and heights. Added this to the question. - Kromster
  • @Kromster Write a macro in excel and see how it does it. - kot-da-vinci
  • 2
    Chart is contained inside the Shape. Shape has Left and Top properties positioning relative to the left-top cell of the sheet. Left and Top can be taken directly from the desired cell: Sheet.Cells[i, j].Left . Do not work with ActiveWorkbook , etc. from Application.ActiveXXX . ru.stackoverflow.com/a/499795/192901 - kami
  • one
    Do you open / create a book? Accordingly, use Application.Workbooks.Add . Workbooks. Application.Workbooks.Add or analogues. This is a function, and it returns a link to the book. Accordingly, we assign the result to our myWorkbook variable and continue to work with myWorkbook , and not with ActiveWorkbook . By analogy - with a sheet. - kami

2 answers 2

One of the options ( proposed here ) to take the range, it has the properties of Left and Top.

 procedure TMyExcelClass.MyProcedure; var sheet, chartObject, r: Variant; begin sheet := fExcel.ActiveWorkBook.Sheets['какой-то лист']; r := sheet.Range['F34']; chartObject := sheet.ChartObjects[1]; chartObject.Left := r.Left; chartObject.Top := r.Top end; 

    The Left property ( Shape object ) of type Single specifies the distance in points from the left edge of the object to the left edge of column A (on the sheet) or the left edge of the diagram area (on the graph). Similarly, the Top property from the top edge of the sheet.

    Thus, to set the desired position of the graph (diagram) relative to a particular cell, you need to add the width of all the cells to the left of the desired one and add the height of all the lines above the required one.

    • "add the width of all the cells to the left of the desired one" .. some kind of overkill. My option is much simpler. - Kromster
    • I agree, your decision is much more elegant. - kot-da-vinci