VBA 添加图表标题

VBA adding chart title

我只想使用 vba 向我的图表添加图表标题。我实际上想对每个 sheet 中的每个图表递归执行此操作,但我什至无法让 1 个图表正常工作。这是我的代码:

Dim chnam
chnam = Left(ActiveSheet.Name, (Len(ActiveSheet.Name) - 9))
With ActiveWorkbook.ActiveSheet.ActiveChart
    .HasTitle = True
    .ChartTitle = chnam
End With

这是我的图表:

当我 运行 我的代码时,我得到:

Object does not support this property or method

试试这个:

Dim chnam as string
chnam = Left(ActiveSheet.Name, (Len(ActiveSheet.Name) - 9))
With ActiveWorkbook.ActiveSheet.ActiveChart
    .HasTitle = True
    .ChartTitle.Select
    .ChartTitle.Text = chnam
End With

尝试将代码更改为:

Dim chnam As String

chnam = Left(ActiveSheet.Name, (Len(ActiveSheet.Name) - 9))

With ActiveWorkbook.ActiveChart
    .HasTitle = True
    .ChartTitle.Select
    .ChartTitle.Text = chnam
End With

...这将适用于活动图表,然后添加 For Each...如果您想应用于活动工作簿中所有工作表中的所有图表。

我遇到了同样的问题,但找不到答案 - 但找到了有效的方法。我的意思是我不知道它为什么起作用但它确实起作用了。

试试这个 - 对我有用。:

With ActiveWorkbook.ActiveChart
.HasTitle = False // added line - not sure why it works!
.HasTitle = True
.ChartTitle.Text = "Chart Title"
End With

希望对您有所帮助。

上述方法在 Office 2016 中对我来说失败了。我不得不使用 Worksheet.Shapes 对象。

Debug.Assert ActiveWorkbook.Charts.Count = 0 ' Strange, but true
ActiveSheet.Shapes(1).Chart.ChartTitle.Text = chnam

下面的子例程适合我。

' Set title of chart with given name on given worksheet
Private Sub RetitleChart(sheetExport As Worksheet, strChartName As String, strChartTitle As String)
  Dim chartOverview As Chart

  Set chartOverview = sheetExport.Shapes(strChartName).Chart
  chartOverview.ChartTitle.Text = strChartTitle
  Set chartOverview = Nothing
End Sub

另一种设置图表标题文本的方法是使用 ChartWizard 方法,因此:

Dim chnam as string
chnam = Left(ActiveSheet.Name, (Len(ActiveSheet.Name) - 9))
ActiveWorkbook.ActiveSheet.ActiveChart.ChartWizard Title:=chnam

熟悉此方法的文档是值得的:

https://msdn.microsoft.com/en-us/library/office/ff838804.aspx

以及 Chart 本身:

https://msdn.microsoft.com/en-us/library/office/ff837379.aspx

(其中有一个 link 到 ChartTitle object 的文档。)

我遇到了同样的问题 - 在我当前的机器上,Excel 2017,而我 6 个月前没有遇到过它;有代码

pchrTheChart.HasTitle = True
pchrTheChart.ChartTitle.Select

第二行会出错;如果我插入一个断点然后不做任何更改继续,它工作正常。

但是,上述解决方案的变体有效;尽管图表刚刚创建并且开始时没有标题,但我必须在打开它之前明确关闭标题,现在它每次都可以正常工作。

pchrTheChart.HasTitle = False
pchrTheChart.HasTitle = True
pchrTheChart.ChartTitle.Select

发帖人说他们不知道为什么会这样;回答,对我来说,我们似乎正在解决一个 VBA 错误,我想这与空处理有关。