宏:录制的宏不起作用

时间:2013-11-11 09:57:03

标签: excel excel-vba vba

我使用Record Macro option在Excel中录制了一个宏。但是,当我运行它时,我得到Error 438,错误框显示Object does not support property or method。这是生成的宏代码。有人可以在这里解释一下:

Sub Macro1()
'
' Macro1 Macro
'

'
    ActiveCell.Range("A1:C1").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=Range("'Sheet2'!$A$4:$C$4")
    ActiveChart.ChartType = xlPie
    Application.CutCopyMode = True
    Selection.Cut
    Sheets("Sheet3").Select
    ActiveSheet.Paste
    Sheets("Sheet2").Select
    ActiveCell.Offset(1, 0).Range("A1").Select

当我调试时,我在Selection.Cut中收到错误。我想知道如何生成记录的宏不工作代码

2 个答案:

答案 0 :(得分:0)

虽然不是一个好方法,但

但将Selection.Cut更改为Selection.Parent.Parent.Cut应该有效。

请记住,尽可能避免使用Select

答案 1 :(得分:0)

应该有效的轻微抛光版本(使用引用并避免选择):

Sub Macro1()
' Macro1 Macro
    Dim ws1 As Worksheet, ws2 As Worksheet
    Set ws1 = ActiveSheet   ' This is likely 'Sheet 1'
    Dim rng As Range
    Set rng = ActiveCell.Range("A1:C1")
    Dim shp As Shape
    Set shp = ws1.Shapes.AddChart
    shp.Chart.SetSourceData Source:=Range("'Sheet2'!$A$4:$C$4")
    shp.Chart.ChartType = xlPie
    Application.CutCopyMode = True
    shp.Cut
    Sheets("Sheet3").Paste
    Set ws2 = Sheets("Sheet2")
    ws2.Activate
    ActiveCell.Offset(1, 0).Range("A1").Select
End Sub