使用 VBA 在辅助 X 轴上放置图表系列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14302560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:43:47  来源:igfitidea点击:

Using VBA to put a chart series on the secondary X axis

excelvbaexcel-vba

提问by Abiel

I have a line chart to which I'm attempting to add, via VBA, a horizontal line at a given Y value. I'm following this guide, which suggests adding a line to an existing chart and then changing its type to scatter, which causes Excel to put the series on the secondary X axis automatically. It can then be formatted further.

我有一个折线图,我试图通过 VBA 在给定的 Y 值处添加一条水平线。我正在遵循本指南,它建议向现有图表添加一条线,然后将其类型更改为散点图,这会导致 Excel 自动将系列放在辅助 X 轴上。然后可以进一步格式化。

My problem is that when doing this with VBA I don't understand how to switch a line onto the secondary X axis. By default all new lines will go on the primary X axis.

我的问题是,使用 VBA 执行此操作时,我不明白如何将一条线切换到辅助 X 轴上。默认情况下,所有新行都将在主 X 轴上。

For example, suppose chrtis a Chart object:

例如,假设chrt是一个 Chart 对象:

' Enable secondary X axis (I think)
chrt.HasAxis(XlAxisType.xlCategory, XlAxisGroup.xlSecondary) = True

Dim se As Series
Set se = chrt.SeriesCollection.NewSeries
se.ChartType = xlXYScatterLinesNoMarkers

' Add a line at Y = 0
se.xValues = Array(0, 1)
se.values = Array(0, 0)

Now, how to get seonto the secondary X axis?

现在,如何se进入第二个 X 轴?

回答by bonCodigo

I followed this link for Excel 2003and recorded a macro. Please note that for Excel 2007 charts have such a unfortunate cases with recording macros. But you get lucky in Excel 2010 again. So watch out for your version if you are going to do it based on a macro and then copy the code...

我按照Excel 2003 的链接并录制了一个宏。请注意,对于 Excel 2007 图表有这样一个带有录制宏的不幸案例。但是您再次在 Excel 2010 中走运。因此,如果您打算根据宏进行操作,然后复制代码,请注意您的版本...

Change sheet and chart name according to yours.

根据您的更改工作表和图表名称。

With Sheets(3).ChartObjects("Chart 1")
     .SeriesCollection(2).AxisGroup = xlSecondary
     .HasAxis(xlCategory, xlPrimary) = True
     .HasAxis(xlCategory, xlSecondary) = True
     .HasAxis(xlValue, xlPrimary) = True
     .HasAxis(xlValue, xlSecondary) = True
     .Axes(xlCategory, xlPrimary).CategoryType = xlAutomatic
     .Axes(xlCategory, xlSecondary).CategoryType = xlAutomatic
  End With