如何通过Excel宏向图表添加文本?

时间:2019-09-19 03:08:16

标签: excel vba excel-charts

使用以下代码通过Excel宏将文本添加到图表吗? 当编译为模块时,它显示“对象不支持此属性或方法”,任何建议或修改后的代码均表示赞赏。谢谢

Set myDocument = Ch.Chart

  myDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, 382, 266, 122, 20).Select

    Selection.ShapeRange.TextFrame.Characters.Text = ThisWorkbook.ActiveSheet.Cells(6, 8)

   With Selection.ShapeRange.TextFrame.Characters

    .Font.Name = "Tahoma"

    .Font.Size = 10

    .Font.Bold = msoTrue

   End With

1 个答案:

答案 0 :(得分:1)

添加文本框等之前无需选择图表。您的代码可以如下重写...

Dim theChartObj As ChartObject
Set theChartObj = Worksheets("Sheet1").ChartObjects("Chart 1") 'change the sheet and chart names accordingly

Dim theChart As Chart
Set theChart = theChartObj.Chart

Dim theTextBox As Shape
Set theTextBox = theChart.Shapes.AddTextbox(msoTextOrientationHorizontal, 382, 266, 122, 20)

With theTextBox.TextFrame.Characters
    .Text = ThisWorkbook.ActiveSheet.Cells(6, 8).Value
    With .Font
        .Name = "Tahoma"
        .Size = 10
        .Bold = msoTrue
    End With
End With