Excel 2013 自动生成的宏 VBA 代码在尝试运行宏时不起作用



我正在尝试在Office 2013中创建非常简单的Excel宏。 宏应创建一个折线图,标题位于 x 轴和 y 轴上。 我转到"开发人员"选项卡,然后选择"录制宏"。 我创建了我的图表,一切看起来都很好。 当我查看自动生成的VBA代码时,它如下所示:

Sub SimplePlotExample()
Range("A1:B11").Select
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$B$11")
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
Selection.Caption = "This is my rows title"
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
Selection.Caption = "This is my y axis title"
Range("A1").Select
End Sub

问题是,当我尝试运行此宏时,不会创建 y 轴标题,而是 x 轴具有用于 y 轴的标题。 如果我直接进入VBA代码,请注释掉"Selection.Caption ="这是我的y轴标题"一行,然后手动将其替换为如下所示的代码,一切正常。

Sub SimplePlotExample()
Range("A1:B11").Select
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$B$11")
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
Selection.Caption = "This is my rows title"
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
'   Add the 2 lines of code below manually to my macro code
ActiveChart.Axes(xlValue, xlPrimary).HasTitle = True
ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Text = "This is my hand-edited y axis title"
'    Selection.Caption = "This is my y axis title"   ### This is the auto-generated line commented out
Range("A1").Select
End Sub

我的问题是.....为什么"自动生成"的VBA代码无法正常工作? 我发现其他线程可能表明这可能是以前版本的Excel的问题,我是否可以假设这也是Excel 2013的问题? 我正在使用Microsoft Office 专业增强版 2013。

谢谢!

在新工作表上尝试一下。

Sub SimplePlotExample()
Range("A1:B11").Select
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$B$11")
With ActiveChart
'chart name
.HasTitle = True
.ChartTitle.Characters.Text = "Chart Name"
'X axis name
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "This is my X-Axis"
'y-axis name
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "This is my Y axis title"
End With
End Sub

最新更新