VBA循环遍历所有图表中的所有系列

时间:2014-01-16 15:13:55

标签: excel vba excel-vba charts

我在使用VBA代码中的几个图表时出现问题。我99.7%肯定这是一个非常容易和快速的解决方案,但我的大脑今天不起作用。

我希望代码循环遍历ActiveSheet上的每个图表,并且对于图表包含的每个数据系列,我希望它添加该系列的最后一个值。在我的例子中,我有9个图表,每个图表中有3个系列(必然会有变化,有些有2个但我离题了)。

我有以下代码

Sub AddLastValue()
Dim myChartObject As ChartObject
Dim myChart As Chart
Dim mySrs As Series
Dim myPts As Points

With ActiveSheet
For Each myChartObject In .ChartObjects
    For Each myChart In .Chart
        For Each mySrs In .SeriesCollection
            Set myPts = .Points
            myPts(myPts.Count).ApplyDataLabels Type:=xlShowValue
        Next
    Next
Next
End With

End Sub

如果我删除了循环代码,只需执行

Set myPts = ActiveSheet.ChartObjects(1).Chart. _
    SeriesCollection(1).Points
myPts(myPts.Count).ApplyDataLabels type:=xlShowValue

然后它适用于特定的图表和系列,所以我很肯定这是我正在弄乱的循环。

有人能告诉我在哪里弄乱了循环代码吗?

2 个答案:

答案 0 :(得分:13)

请尝试以下代码:

Sub AddLastValue()
    Dim myChartObject As ChartObject
    Dim mySrs As Series
    Dim myPts As Points

    With ActiveSheet
        For Each myChartObject In .ChartObjects
            For Each mySrs In myChartObject.Chart.SeriesCollection
                Set myPts = mySrs.Points
                myPts(myPts.Count).ApplyDataLabels Type:=xlShowValue
            Next
        Next
    End With

End Sub

答案 1 :(得分:1)

不适用于空值。

此代码查找最后一个非空值,然后添加标签。

@RequestMapping(value = "/birtReport1", method = RequestMethod.GET)
@ApiOperation("Download Report")
public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        //get report name and launch the engine
        resp.setContentType("text/html");
//      resp.setContentType( "application/pdf" ); 
        //resp.setHeader ("Content-Disposition","inline; filename=test.pdf");       
        String reportName = "/Documents/workspace/Birt/MyFirstReport.rptdesign";
        ServletContext sc = req.getSession().getServletContext();
        this.birtReportEngine = BirtEngine.getBirtEngine(sc);
        IReportRunnable design;
        try
        {
            //Open report design
            design = birtReportEngine.openReportDesign( reportName );
            //create task to run and render report
            IRunAndRenderTask task = 
            birtReportEngine.createRunAndRenderTask( design );      
            String[] values = {"10096", "10094"};
            task.setParameterValue("idCatalogue",values);
            HTMLRenderOption options = new HTMLRenderOption();
        options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
            options.setOutputStream(resp.getOutputStream());
            task.setRenderOption(options);

            //run report
            task.run();
            task.close();
        }catch (Exception e){

            e.printStackTrace();
            throw new ServletException( e );
        }
    }