【问题标题】:Excel VBA - random runtime errorsExcel VBA - 随机运行时错误
【发布时间】:2018-07-04 12:03:09
【问题描述】:

我对 Excel VBA 非常陌生,但设法在员工时间表中创建了三个按钮。所有按钮都按需要工作,但是,一个特定按钮会导致随机问题 - 大约 90% 的时间它可以工作,但有时它会导致 Excel 崩溃或出现错误,例如运行时错误'-2147417848 (800 10 108) ':自动化错误调用的对象已与其客户端断开连接。其他时候是类似的消息,说对象“范围”的方法“插入”失败。 它发生在不同计算机上不同版本的 Excel 中。任务并不复杂,但我的 VBA 知识却步履维艰。
用户单击按钮以设置名为“Timesheet”的工作表中的每个格式化行,即单击“Timesheet”中的按钮从 sheet4 复制一行(格式化并包含公式)并将其插入到按钮上方的“Timesheet”中。
如果有人能提出不会导致 Excel 崩溃的替代代码,我将不胜感激 - 非常感谢!

Sub NewSlot()

' NewSlot Macro used in Timesheet
'
    'turn protection off
    Worksheets("Sheet4").Unprotect Password:="mypasswd"
    Worksheets("Timesheet").Unprotect Password:=" mypasswd "

    ' select row 8 in sheet4
    Sheets("Sheet4").Select
    Rows("8").Select
    Selection.Copy

    ' go back to timesheet
    Sheets("Timesheet").Select

    ' insert copied row
    Dim r As Range
    Set r = ActiveSheet.Buttons(Application.Caller).TopLeftCell
    Range(Cells(r.Row, r.Column), Cells(r.Row, r.Column)).Offset(0, 0).Select

    Selection.Insert shift:=xlDown
    Application.CutCopyMode = False


    'turn protection on
    Worksheets("Sheet4").Protect Password:=" mypasswd "
    Worksheets("Timesheet").Protect Password:=" mypasswd"

End Sub

【问题讨论】:

标签: excel vba


【解决方案1】:

如果您要使用 VBA 反复修改受保护的工作表,请取消保护,然后使用 UserInterfaceOnly:=True 保护一次。

sub protectOnce()
    worksheets("Timesheet").unprotect password:="mypasswd"
    worksheets("sheet4").unprotect password:="mypasswd"
    worksheets("Timesheet").protect password:="mypasswd", UserInterfaceOnly:=True
    worksheets("sheet4").protect password:="mypasswd", UserInterfaceOnly:=True
end sub

完成此操作后,您无需取消保护即可使用 VBA 进行修改。如果您出于其他原因必须取消保护,请使用 UserInterfaceOnly:=True 重新保护它。

这大大减少了您的 NewSlot 代码。避免使用 Select 和 Activate 被认为是“最佳实践”,尤其是跨工作表。

Sub NewSlot()

    ' select row 8 in sheet4
    workSheets("Sheet4").Rows("8").Copy

    ' go back to timesheet
    with workSheets("Timesheet")
        ' insert copied row
        Dim r As Range
        Set r = .Buttons(Application.Caller).TopLeftCell
        .Cells(r.Row, "A").entirerow.Insert shift:=xlDown
    end with

End Sub

【讨论】:

  • 非常感谢,不胜感激!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多