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

三世轮回 提交于 2019-12-12 14:20:23

问题


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.

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


回答1:


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

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;



回答2:


Simply record a Macro while you add a Histogram to your sheet.

Stop recording and press Alt+F11 to open the Visual Basic Editor. Open the recoded macro and convert/compare the VBA to C# code.



来源:https://stackoverflow.com/questions/46959831/c-sharp-why-histogram-does-not-work-in-excel-2016

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!