Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
In Excel, go to Insert -> Diagram… (Now Diagram Gallery window will open), Double click on a diagram to display it on Excel.
I am trying to calculate the position of the Diagram using the below code

C#
Pictures pictures = ws.Pictures(missing) as Pictures;
if (pictures != null)
{
foreach (object pic in pictures)
{
 Picture picObj = pic as Picture;
if (picObj != null && picObj.Visible)
{
if (firstCol > picObj.TopLeftCell.Column)
firstCol = picObj.TopLeftCell.Column;
if (firstRow > picObj.TopLeftCell.Row)
firstRow = picObj.TopLeftCell.Row;
if (lastCol < picObj.BottomRightCell.Column)
lastCol = picObj.BottomRightCell.Column;
if (lastRow < picObj.BottomRightCell.Row)
lastRow = picObj.BottomRightCell.Row;
 }
}
}


But this is returning wrong value for Rows and Columns
I am using another "forloop" for calculating Shapes and Diagram objects position is calculated correctly. But as the picture Object setting the wrong value i am getting error for the below line.
PrintRange = ws.get_Range(ws.Cells[firstRow, firstCol], ws.Cells[lastRow, lastCol]);

Could some one suggest how we can avoid the Diagrams when using the Picture Object or how to calculate the cell position correctly
Posted

1 solution

The diagrams are stored in Shapes ;)

You need to go through the collection of shapes in worksheet and find a diagram by the name or by the index.

VBA code:
VB
'gets the address of diagram
Function GetDiagramPosition(wsh As Worksheet, sName As String) As String
Dim shDgm As Shape, i As Integer

For i = 1 To wsh.Shapes.Count
    Set shDgm = wsh.Shapes(i)
    If shDgm.Name = sName Then Exit For
Next

GetDiagramPosition = shDgm.TopLeftCell.Address & ":" & shDgm.BottomRightCell.Address

End Function


C# code translated on: http://www.carlosag.net/tools/codetranslator/[^]
C#
string GetDiagramPosition(Worksheet wsh, string sName) {
       Shape shDgm;
       for (int i = 1; (i <= wsh.Shapes.Count); i++) {
           shDgm = wsh.Shapes(i);
           if ((shDgm.Name == sName)) {
               break;
           }
       }
       return (shDgm.TopLeftCell.Address + (":" + shDgm.BottomRightCell.Address));
   }


Result: "$A$3:$H$7"

To use the code above, you need to set reference to Office.Interop.Excel[^]
 
Share this answer
 
v2
Comments
VJ Reddy 1-May-12 20:56pm    
Good answer 5!
Maciej Los 2-May-12 7:41am    
Thank you ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900