Search code examples
c#vstoexcel-charts

C# - why Histogram does not work in Excel 2016?


I have excel 2016 vsto application build in c#. I have a chart control and want to set chart type to the histogram. I can select this chart from excel but I am not able set this chart type programmatically. enter image description here

In other words, I am not able to find histogram chart type in the XlChartType enum.


Solution

  • In such cases you should always open Object Browser in excel macros and and search for what you are looking for

    histogram

    As you can see from object browser, the value for histogram is 118 or 76 in hex. You can use the same in your code directly by defining a constant

    Edit-1: The code

    Debugging your code below I found a issue

    Worksheet sheet1 = Globals.Factory.GetVstoObject(Globals.Sheet1.Application.Worksheets[1]);
    //chartTest
    Excel.ChartObject myChart = (Excel.ChartObject)sheet1.ChartObjects("chartTest");
    myChart.Chart.SetSourceData(sheet1.Range["A1", "A51"]);
    myChart.Chart.Type = 118;
    

    What you need to do is assign 118 to ChartType and not Type. Below code worked fine for me

    Worksheet sheet1 = Globals.Factory.GetVstoObject(Globals.Sheet1.Application.Worksheets[1]);
    //chartTest
    Excel.ChartObject myChart = (Excel.ChartObject)sheet1.ChartObjects("chartTest");
    myChart.Chart.SetSourceData(sheet1.Range["A1", "A51"]);
    Excel.XlChartType myType = (Excel.XlChartType)118;
    
    myChart.Chart.ChartType = myType;