我尝试在出错时使用Goto,但是即使出现错误,它似乎也会跳过这个,或者即使没有发生错误也会这样做,这取决于我将它放在脚本中的位置。
此行代码中出现运行时错误:
Range(Worksheets("Search Engine").Cells(9, 1), Worksheets("Search Engine").Cells(Endcolumn, Endrow + 2)).Select Selection.RowHeight = 20` when `Endcolumn = 0
答案 0 :(得分:4)
根据您的评论,当Application-defined or object-defined error
变量为0时,您会看到Endcolumn
。这种情况正在发生,因为Excel Range
是基于1的,而不是基于0的,意味着永远不会有第0列。
由于您似乎对错误处理最感兴趣,因此大致应该如何处理:
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