发生错误时是否可以自动保护工作表?
我曾尝试在错误上使用Goto,但即使发生错误,它似乎也跳过了这一点,或者即使没有发生错误,也依赖于将其放置在脚本中的位置。
运行时错误发生在这行代码中:
Range(Worksheets("Search Engine").Cells(9, 1), Worksheets("Search Engine").Cells(Endcolumn, Endrow + 2)).Select Selection.RowHeight = 20` when `Endcolumn = 0
根据您的评论,当您的Endcolumn
variables为0时,您会看到Application-defined or object-defined error
。这是因为Excel Range
是基于1而不是基于0的,这意味着从不存在列0。
由于您似乎对error handling特别感兴趣,下面大概是应该如何处理的:
Sub ErrorExample() On Error GoTo ErrHandler ' Set the Error Handling Condition ' in this case, if an error occurs ' goto the ErrHandler label ' do stuff Debug.Print "I am in `do stuff` code" Range(Worksheets("Search Engine").Cells(9, 1), Worksheets("Search Engine").Cells(Endcolumn, Endrow + 2)).Select Selection.RowHeight = 20 Exit Sub ' Exit from the Sub gracefully and do not run the ' following lines of code (if this is not ' included, the ErrHandler code will run in all ' cases, not just error cases Debug.Print "I will never run" ErrHandler: Debug.Print "I am in the error code" ' Code to run in case of error ThisWorkbook.Worksheets("Search Engine").Protect ' protect your sheet On Error GoTo 0 ' Reset the error handling condition End Sub