vba 在 Excel 中设置 x 轴的最大值和最小值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17796904/
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 16:12:41  来源:igfitidea点击:

Setting maximum and minimum values for x-axis in Excel

excelexcel-vbavba

提问by Sara E

I have a graph that has dates on the x-axis and I'm trying to set maximum and minimum values for this axis using an Excel VBA. I defined MinXAxis and MaxXAxis values in the same sheet and here is my code:

我有一个在 x 轴上有日期的图表,我正在尝试使用 Excel VBA 为该轴设置最大值和最小值。我在同一张表中定义了 MinXAxis 和 MaxXAxis 值,这是我的代码:

Sub UpdateChartAxes()

   With ActiveSheet.ChartObjects("Chart 1").Chart

      .Axes(xlCategory).MinimumScaleIsAuto = False
      .Axes(xlCategory).MinimumScale = Range("MinXAxis").Value
      .Axes(xlCategory).MaximumScaleIsAuto = False
      .Axes(xlCategory).MaximumScale = Range("MaxXAxis").Value

   End With

End Sub

When I run this code I get error 400 with no explanation about the error. Any ideas what might be going wrong?

当我运行此代码时,我收到错误 400,但没有对错误进行解释。任何想法可能会出错?

采纳答案by Andy G

Axis.MinimumScale Property

Axis.MinimumScale 属性

Returns or sets the minimum value on the value axis. Read/write Double.

返回或设置值轴上的最小值。读/写双。

You should be applying these properties to the value axis xlValue, not the Category axis.

您应该将这些属性应用于值轴xlValue,而不是类别轴。

Setting this property will also set MinimumScaleIsAuto = Falseso you won't need those lines.

设置此属性也将设置,MinimumScaleIsAuto = False因此您将不需要这些行。

AddedIf you use a column, bar, line, etc., graph then these have a Value and a Category axis. You can only set the Minimum or Maximum for the Value axis. Even if you swap them around (x - y) there is still only one Value and one Category axis. EditedAn exception to this is if dates are used as the Category axis, in which case Excel enables the Scale settings, as it recognises them as values.

添加如果您使用柱形、条形、线形等图形,则它们具有值和类别轴。您只能为值轴设置最小值或最大值。即使您在 (x - y) 周围交换它们,仍然只有一个值和一个类别轴。已编辑一个例外情况是,如果日期用作类别轴,在这种情况下 Excel 会启用“比例”设置,因为它会将它们识别为值。

If, instead, you use a Scatter graph, then this has both X-Values and Y-Values, and each of these value axescan be given maxima and minima.

相反,如果您使用散点图,则它同时具有 X 值和 Y 值,并且这些值轴中的每一个都可以给出最大值和最小值。

By far the easiest way to prove all this is to double click on an axis and see whether the Axis Optionsallows you to set a minimum and maximum.

到目前为止,证明这一切的最简单方法是双击一个轴,看看它是否Axis Options允许您设置最小值和最大值。

回答by Jaycal

At the beginning of the code, add

在代码开头添加

On Error GoTo ShowErrDescription.

After End Withand before End Sub, add the following code

之后End With和之前End Sub,添加以下代码

Exit Sub
ShowErrDescription:
MsgBox Err.Description

This should at least give you a little more information about the error.

这至少应该为您提供有关错误的更多信息。