如何在Shapes()中引用图表标题?

我想根据工作表中的某些现有数据在新选项卡中格式化图表。 我可以使用“另存为模板”来logging模式,但是我想创build一个每次都会创build相同格式的macros。 不过,我提到图表有一些问题。 这是我的代码。

Sub Macro1() Dim GraphTab As Object Set GraphTab = ActiveSheet 'Change everything to Times New Roman With ActiveSheet.Shapes(GraphTab).TextFrame2.TextRange.Font .NameComplexScript = "Times New Roman" .NameFarEast = "Times New Roman" .Name = "Times New Roman" .Size = 10 End With End Sub 

我从这一行收到一条错误消息With ActiveSheet.Shapes(GraphTab).TextFrame2.TextRange.Font

理想情况下,我也希望每次手动更改选项卡名称时都更新GraphTab 。 那可能吗?

根据您最后的评论,此代码已经过testing,可以产生所需的结果。

 Sub Macro1() Dim ws As Worksheet Set ws = Sheets("NewChartSheet") ' change name as needed ws.Range("A1").Formula = "=RIGHT(CELL(""filename"",A1),LEN(CELL(""filename"",A1))-FIND(""]"",CELL(""filename"",A1))) Dim cht As ChartObject Set cht = ws.ChartObjects(1) 'since just one chart on page, it's the first one in the collection With cht.Chart.ChartTitle With .Format.TextFrame2.TextRange.Font .NameComplexScript = "Times New Roman" .NameFarEast = "Times New Roman" .Name = "Times New Roman" .Size = 10 End With .Caption = "=NewChartSheet!R1C1" End With End Sub 

要了解图表标题如何设置为在表名更改时自动更改,请参阅下面的内容:

  1. .Caption = "=NewChartSheet!R1C1"将图表标题设置为等于单元格A1中的值
  2. ws.Range("A1").Formulaws.Range("A1").Formula设置为显示工作表名称。
  3. A1的公式使用CELL函数的filename参数,它返回引用单元格的完整文件path,文件名和表名。
  4. 该公式操作文件名的格式进一步返回表名。

也许这是你一直在寻找的解决scheme:

 With Sheet1.ChartObjects("Chart 1").Chart.ChartTitle .Text = "test" .Font.FontStyle = "Times New Roman" .Font.Size = 10 End With 

如果使用工作表的代码名称而不是工作表名称,那么当您更改图表工作表的名称时,代码仍然可以工作。 如果你打算改变图表名称,那么我会像这样整合一个循环

 For Each cht In Sheet1.ChartObjects With cht.Chart.ChartTitle .Text = "test" .Font.FontStyle = "Times New Roman" .Font.Size = 10 End With Next cht