文章背景:有一组x-y的数据,想通过录制宏
的方式,实现画图的自动化。本文以散点图为例,需要在图中添加坐标轴的标题。录制好宏后,运行代码时,报错如下:
http://mpvideo.qpic.cn/0b785maamaaabyaf22uajbpvb26da3vqabqa.f10002.mp4?dis_k=a788fc54bd6bf3b30a428605394aa7a5&dis_t=1663655191&vid=wxv_1554499370312597506&format_id=10002&support_redirect=0&mmversion=false
通过查阅相关资料,发现程序报错的可能原因如下:
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的相关代码,
代码语言:javascript复制 ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Text = "y"
Selection.Format.TextFrame2.TextRange.Characters.Text = "y"
ActiveChart.Axes(xlCategory).AxisTitle.Select
ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Text = "x"
Selection.Format.TextFrame2.TextRange.Characters.Text = "x"
(2)添加如下代码:
代码语言:javascript复制 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)(https://docs.microsoft.com/zh-cn/office/vba/api/Excel.Chart.Axes)
[2] Run-time Error '424': Object Required when setting AxisTitle.Text(https://stackoverrun.com/cn/q/8203932)
[3] Excel 2007 VBA Problem setting Axis Title(https://stackoverflow.com/questions/7041428/excel-2007-vba-problem-setting-axis-title)