【问题标题】:Making axis title in Excel chart with VBA使用VBA在Excel图表中制作轴标题
【发布时间】:2019-03-09 17:56:23
【问题描述】:

我用 VBA 创建了一个 Excel 图表,然后格式化轴标题和字体大小。以下代码适用于水平轴

cht.SetElement msoElementPrimaryCategoryAxisTitleAdjacentToAxis
cht.Axes(xlCategory, xlPrimary).AxisTitle.Text = "Factor of Safety"
cht.Axes(xlCategory, xlPrimary).AxisTitle.Format.TextFrame2.TextRange.Font.Size = 15

但是,垂直轴的类似代码

cht.SetElement msoElementPrimaryValueAxisTitleAdjacentToAxis
cht.Axes(xlValue, xlPrimary).AxisTitle.Text = "Depth [mCD]"
cht.Axes(xlValue, xlPrimary).AxisTitle.Format.TextFrame2.TextRange.Font.Size = 15

导致错误 424“需要对象”。你能告诉我发生了什么吗?

【问题讨论】:

  • 你能发布完整的代码吗?当您到达垂直轴时,您可能已经破坏了cht 对象。你能检查cht 在你到达它时是否仍然是一个对象吗?
  • @Zac:实际上这两段代码是放在一起的,中间没有代码,这就是为什么我无法理解并在这里发布问题的原因。当然,我没有犯那个明显的错误。这两个部分的前面是启动图表的标准代码。设置 cht = ActiveSheet.Shapes.AddChart2(Style:=240,XlChartType:=xlXYScatter,Left:=Cells(2, 9).Left,Top:=Cells(2, 9).Top,Width:=350,Height: =500).图表
  • 你能在尝试设置msoElementPrimaryValueAxisTitleAdjacentToAxis之前尝试销毁cht对象并重置它吗?

标签: excel vba charts


【解决方案1】:

在最新版本的 Excel 中,您可以使用带有命名常量的 SetElement 向图表添加功能。这似乎更容易,但就其实际作用而言,它不太直观,而且可能不可靠。

所以不要这样:

cht.SetElement msoElementPrimaryValueAxisTitleAdjacentToAxis
cht.Axes(xlValue, xlPrimary).AxisTitle.Text = "Depth [mCD]"
cht.Axes(xlValue, xlPrimary).AxisTitle.Format.TextFrame2.TextRange.Font.Size = 15

这样做:

cht.Axes(xlValue, xlPrimary).HasTitle = True
cht.Axes(xlValue, xlPrimary).AxisTitle.Text = "Depth [mCD]"
cht.Axes(xlValue, xlPrimary).AxisTitle.Format.TextFrame2.TextRange.Font.Size = 15

【讨论】:

    【解决方案2】:

    另一个从 Jon Peltier 的答案中扩展而来的答案:

    Charts.Add
    With ActiveChart        
        .Axes(xlValue, xlPrimary).HasTitle = True ' must set outside with       
        With .Axes(xlValue, xlPrimary)      
            .AxisTitle.Text = "Depth [mCD]"
            .AxisTitle.Format.TextFrame2.TextRange.Font.Size = 15       
        End With        
    End With
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多