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

时间:2017-05-17 19:58:54

标签: excel vba excel-vba

我正在尝试在Office 2013中创建一个非常简单的Excel宏。宏应创建一个在x和y轴上带有标题的折线图。我去了#34;开发人员"选项卡并选择"录制宏"。我创建我的图表,一切看起来都很好。当我查看自动生成的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 Professional Plus 2013。

谢谢!

1 个答案:

答案 0 :(得分:0)

在新表上试试。

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