如何在excel中为气泡图添加数据标签

时间:2016-01-08 04:37:31

标签: excel excel-vba bubble-chart vba

您好我想在我的气泡图中添加自定义数据标签。我的代码如下。目前数据标签指的是XValues。我希望我的数据标签填充气泡大小。你会介意我如何自定义下面的代码吗?

我尝试添加.DataLabel.Text =“txt”,但我收到了以下内容 错误: 运行时错误'438':对象不支持此属性或方法

Public Sub CreateMultiSeriesBubbleChart()
If (Selection.Columns.Count <> 4 Or Selection.Rows.Count < 3) Then
    MsgBox "Selection must have 4 columns and at least 2 rows"
    Exit Sub
End If

Dim red, green, blue As Integer


Dim bubbleChart As ChartObject
Set bubbleChart = ActiveSheet.ChartObjects.Add(Left:=Selection.Left, Width:=600, Top:=Selection.Top, Height:=400)
bubbleChart.Chart.ChartType = xlBubble
Dim r As Integer

For r = 2 To Selection.Rows.Count
    With bubbleChart.Chart.SeriesCollection.NewSeries
        .Name = "=" & Selection.Cells(r, 1).Address(External:=True)
        .XValues = Selection.Cells(r, 2).Address(External:=True)
        .Values = Selection.Cells(r, 3).Address(External:=True)
        .BubbleSizes = Selection.Cells(r, 4).Address(External:=True)
        .Format.Fill.Solid
        .Format.Fill.ForeColor.RGB = RGB(61, 161, 161)
     '   .DataLabel.Text = "txt"
    End With

Next

bubbleChart.Chart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
bubbleChart.Chart.Axes(xlCategory, xlPrimary).AxisTitle.Text = "=" & Selection.Cells(1, 2).Address(External:=True)

bubbleChart.Chart.SetElement (msoElementPrimaryValueAxisTitleRotated)
bubbleChart.Chart.Axes(xlValue, xlPrimary).AxisTitle.Text = "=" & Selection.Cells(1, 3).Address(External:=True)

bubbleChart.Chart.SetElement (msoElementPrimaryCategoryGridLinesMajor)
bubbleChart.Chart.Axes(xlCategory).MinimumScale = 0

End Sub

我的输入样本:

Label          Hour Day count
01-SUNDAY       14  1   1
01-SUNDAY       19  1   1
02-MONDAY       12  2   1
02-MONDAY       13  2   1
02-MONDAY       14  2   2
02-MONDAY       16  2   2

2 个答案:

答案 0 :(得分:2)

DataLabel.TextPoint的方法,而不是NewSeries

此代码:

For r = 2 To Selection.Rows.Count
    With bubbleChart.Chart.SeriesCollection.NewSeries
        [...]
        .DataLabel.Text = "txt"
    End With 
Next

...尝试标记系列,但失败了。

认识到此代码来自另一个着名的“多系列气泡图”示例,我们只需要处理每个系列1个数据点,这是一个逻辑假设,这使得以下代码成为解决方案:

For r = 2 To Selection.Rows.Count
    With bubbleChart.Chart.SeriesCollection.NewSeries
        [...]
        .Points(1).HasDataLabel = True
        .Points(1).DataLabel.Text = "txt"
    End With 
Next

答案 1 :(得分:1)

不使用VBA,右键单击气泡并选择Add Data Labels。然后,右键单击数据标签,然后单击“设置数据标签格式”。在“标签选项”下,选择“从单元格中输入值”并指定包含您要使用的标签的单元格。