插入行时出现Excel Automation错误

时间:2015-01-13 23:45:32

标签: excel vba excel-vba

我有一个大问题,它让我疯狂。我有一段非常简单的代码,它应该复制一行并将其添加到活动行下方,并在代码开头添加验证,以检查是否允许您在该特定行上添加行。

当您第一次进入工作表时,宏工作正常。但是,只要我在工作表上的任何单元格中输入任何内容,代码就会因自动化错误而爆炸。请说有人之前已经找到了这个并且有解决方法吗?

它不喜欢的线条如下所示。 Selection.Insert Shift:=xlDown

Sub Staffing_AddRow()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    ActiveCell.Select
    Cells(ActiveCell.Row, 223).Select
    If ActiveCell.Value = "Y" Then
        ActiveSheet.Unprotect Password:="PasswordGoesHere"
        '------------------------------------
        ActiveCell.Rows("1:1").EntireRow.Select
        Selection.Copy
        Selection.Insert Shift:=xlDown
        '------------------------------------
        Cells(ActiveCell.Row, 13).Select
        ActiveSheet.Protect Password:="PasswordGoesHere"
    Else
        If Response = MsgBox("You can't insert a row here!", _
            vbCritical, "Warning") Then
        Cells(ActiveCell.Row, 13).Select
        End If
        Cells(ActiveCell.Row, 13).Select
    End If
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

当它尝试在工作表中粘贴该特定行时,我得到Run-time error '-2147417848 (80010108)': Automation error the object invoked has disconnected from its clients

1 个答案:

答案 0 :(得分:2)

试试这个:使用With ActiveSheet

Sub Staffing_AddRow()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    ActiveCell.Select

    'CHANGES BEGIN HERE
    With ActiveSheet
        If .Cells(ActiveCell.row, 223).Value = "Y" Then
            ActiveSheet.Unprotect Password:="PasswordGoesHere"
            '------------------------------------
            ActiveCell.Rows("1:1").EntireRow.Select
            Selection.Copy
            Selection.Insert Shift:=xlDown
            '------------------------------------
            .Cells(ActiveCell.row, 13).Select
            ActiveSheet.Protect Password:="PasswordGoesHere"
        Else
            If Response = MsgBox("You can't insert a row here!", _
                vbCritical, "Warning") Then
            .Cells(ActiveCell.row, 13).Select
            End If
            .Cells(ActiveCell.row, 13).Select
        End If
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic
    End With
End Sub

另请参阅:How to avoid using select statements in macros