Reputation: 37
I have a code that removes the data label(s) from a customized pie chart if the value of the cell is 0%. However, since my code loops so that the data changes, i completely lose the label for that particular category so when a new set of data is added and the value is not zero the label does not appear any more. How do I do it so that when the value is 0 the data label is removed but when the value is anything but zero then it would reappear, essentially resetting the original set up of the chart so that all values/categories have data labels.
Sub ChartLoop()
Range("D2").Select
ActiveCell.Range("C1:E1").Select
Dim myPDF As String
Dim i As Long
For counter = 2 To 21
Sheets("CF").Select
Range("'CF'!$D$" & counter & ":$F$" & counter).Select 'numbers
Selection.Copy
Sheets("CF-Chart").Select
Range("B1:B3").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
'this is for removing the data labels
Dim iPts As Integer
Dim nPts As Integer
Dim aVals As Variant
Dim srs As Series
ActiveSheet.ChartObjects("Chart 5").Activate
For Each srs In ActiveChart.SeriesCollection
With srs
If .HasDataLabels Then
nPts = .Points.Count
aVals = .Values
For iPts = 1 To nPts
If aVals(iPts) = 0 Then
.Points(iPts).HasDataLabel = False
End If
Next
End If
End With
Next
ActiveSheet.ChartObjects("Chart 5").Activate
ActiveChart.ChartArea.Select
myPDF = "\\stchsfs\arboari$\Profile-Data\Desktop\Export Trial1\c2-" & Sheets("CF").Range("C" & i + 2).Value2 & ".pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=myPDF, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
i = i + 1
Next counter
End Sub
The first chart is how my regular chart would look like. The second chart is where I would want to remove the data label with the value 0 but keep the data label with categories and value for the other ones with value >0.
Thanks!
Upvotes: 2
Views: 3248
Reputation: 5450
Maybe change
If aVals(iPts) = 0 Then
.Points(iPts).HasDataLabel = False
End If
to this?
If aVals(iPts) = 0 Then
.Points(iPts).HasDataLabel = False
.DataLabels.ShowValue = False
Else
.Points(iPts).HasDataLabel = True
.DataLabels.ShowValue = True
End If
EDIT 4-27-2018
Okay... I've tested this solution and it works for me. Not the most elegant but it works. Let me know if it works for you -
ActiveSheet.ChartObjects("Chart 5").Activate
With ActiveChart.SeriesCollection(1)
For i = 1 To .Points.Count
If .Points(i).HasDataLabel = False Then
.Points(i).Select
ActiveChart.SetElement (msoElementDataLabelShow)
If .Points(i).DataLabel.Text = 0 Then
.Points(i).HasDataLabel = False
.Points(i).DataLabel.ShowValue = False
End If
ElseIf .Points(i).DataLabel.Text = 0 Then
.Points(i).HasDataLabel = False
.Points(i).DataLabel.ShowValue = False
End If
Next i
End With
Upvotes: 1