实时错误424 要求对象_VBA: 运行时错误‘424:要求对象(设置坐标轴标题时)

时间:2024-10-22 07:21:31

    文章背景:有一组x-y的数据,想通过录制宏的方式,实现画图的自动化。本文以散点图为例,需要在图中添加坐标轴的标题。录制好宏后,运行代码时,报错如下:

通过查阅相关资料,发现程序报错的可能原因如下:

Although you have recorded using a macro and it should automatically play back, it doesn't seem to in the case of label text. You first have to create the AxisTitle object - an axis doesn't automatically have one.

解决方法

(1)删去宏内有关Axes的相关代码,

   (xlValue, xlPrimary). = "y"   Selection.Format.TextFrame2.TextRange.Characters.Text = "y"   (xlCategory).AxisTitle.Select   (xlValue, xlPrimary). = "x"   Selection.Format.TextFrame2.TextRange.Characters.Text = "x"

(2)添加如下代码:

    With ActiveChart       .Axes(xlCategory, xlPrimary).HasTitle = True       .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "x"       .Axes(xlValue, xlPrimary).HasTitle = True       .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "y"    End With

运行新的程序后,得到所需要的结果。

相关资料:

[1] Chart 方法 (Excel)(/zh-cn/office/vba/api/)

[2] Run-time Error '424': Object Required when setting (/cn/q/8203932)

[3] Excel 2007 VBA Problem setting Axis Title(/questions/7041428/excel-2007-vba-problem-setting-axis-title)