Select alternate points and move labels above/below

我的未来我决定 提交于 2020-01-05 22:50:12

问题


I am fairly new to VBA and trying to select alternating points to place datalabels above and below.

Here is my code that is currently placing a datalabel below point 1 which I want, but then I want the 3rd point's label to be placed below as well, and the other ones above. I have tried many different loops and codes but nothing seems to work and I'm not sure why it seems to copy and paste instead of move the label.

     For x = 1 To ActiveChart.SeriesCollection(1).Points.Count

        With ActiveChart.SeriesCollection(1).Points(x).DataLabel
             .Position = xlLabelPositionBelow
             .Orientation = xlHorizontal
        End With
    x = x + 2

    Next x

    For x = 2 To ActiveChart.SeriesCollection(1).Points.Count

        With ActiveChart.SeriesCollection(1).Points(x).DataLabel
            .Position = xlLabelPositionAbove                            
            .Orientation = xlHorizontal
        End With
    x = x + 2

    Next x

This is what my code currently produces:

Here is what I would like it to do:

I feel like it is something simple that I am missing if this is possible. So any help would be greatly appreciated. Is it possible there is an easier way? Thank you in advance.


回答1:


The problem appears to be that you are 'over-iterating' x. Where you want x to go up by two, you're actually saying "x = x + 2" and THEN also saying "+ 1 x" (which is what Next does). You could solve this above by changing your For Loops to say "For x = 1 to 3 Step 2". Then when you loop with "Next x", it will add 2 instead of just 1.

However, I recommend you do it like the following, as it is (in my opinion) a little clearer that you want something for an even x, and something for an odd x:

 For x = 1 To ActiveChart.SeriesCollection(1).Points.Count
    With ActiveChart.SeriesCollection(1).Points(x).DataLabel
    If x Mod 2 = 1 Then 'If x is odd, put label below point

        .Position = xlLabelPositionBelow
        .Orientation = xlHorizontal
    Else 'if x is even, put label above point
        .Position = xlLabelPositionAbove
        .Orientation = xlHorizontal
    End If

    End With

Next x



回答2:


ActiveChart.SeriesCollection(1).Points(1).DataLabel.Position = xlLabelPositionBelow
ActiveChart.SeriesCollection(1).Points(2).DataLabel.Position = xlLabelPositionAbove
ActiveChart.SeriesCollection(1).Points(3).DataLabel.Position = xlLabelPositionBelow

For x = 4 to ActiveChart.SeriesCollection(1).Points.Count
    ActiveChart.SeriesCollection(1).Points(x).DataLabel.Position = xlLabelPositionAbove
Next


来源:https://stackoverflow.com/questions/31857625/select-alternate-points-and-move-labels-above-below

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