运行时错误'1004':选择范围类失败的VBA 2010方法

时间:2015-11-11 12:27:25

标签: excel vba

我正在尝试在表格中填写公式。我正在使用的代码是一个录制的宏,它可以正常工作,直到我将它连接到一个按钮。当我这样做时,它会给出一个

  

“运行时错误'1004':选择范围类的方法失败”

这是代码,我可以看到它没有错。当我点击调试时,突出显示第二行

Private Sub CommandButton2_Click()

Sheets("DB2 Totbel").Select

Range("B2:D2").Select

Selection.AutoFill Destination:=Range("B2:D15000"), Type:=xlFillDefault

Range("B2:D15000").Select

picture of code in VBA

enter image description here

2 个答案:

答案 0 :(得分:0)

B2的父级工作表有一些含糊不清:D2和B2:D15000范围。

Private Sub CommandButton2_Click()
    Application.Calculation = xlManual
    With Sheets("DB2 Totbel")
        .Range("B2:D2").AutoFill Destination:=.Range("B2:D15000"), Type:=xlFillDefault
        'uncomment these is you need to activate the DB2 Totbel worksheet
        'and select B2:D15000
        '.Activate
        '.Range("B2:D15000").Select
    End With
    Application.Calculation = xlCalculationAutomatic
End Sub

Range.FillDown method交替使用。

Private Sub CommandButton2_Click()
    Application.Calculation = xlManual
    With Sheets("DB2 Totbel")
        .Range("B2:D15000").FillDown
    End With
    Application.Calculation = xlCalculationAutomatic
End Sub

记录的宏非常冗长,并且过多地使用了.Select.Activate命令。有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros

答案 1 :(得分:0)

  Private Sub CommandButton2_Click()

    Application.Calculation = xlCalculationManual

        With Sheets("DB2 Totbel")
            .Range("B2:D2").AutoFill Destination:=.Range("B2:D15000"), Type:=xlFillDefault
        End With

    End Sub