【发布时间】: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
【问题讨论】:
-
如果您要使用 VBA 修改受保护的工作表,请取消保护,然后使用 UserInterfaceOnly:=True 保护一次(请参阅 this)。完成后,您无需取消保护即可使用 VBA 进行修改。如果您出于其他原因必须取消保护它,请使用 UserInterfaceOnly:=True 重新保护它。
-
看来你和 T Wilken Dynamic button - Runtime error 1004 - Unable to get the Buttons property of the Worksheet class 是同一个老师。您的时间表密码不匹配。考虑将目标范围作为参数传递。这可能是一个难以解决的错误。听从@Jeeped 的建议。