0

我曾尝试在错误时使用 Goto,但即使发生错误,它似乎也会跳过此操作,或者即使没有发生错误也执行此操作,具体取决于我将其放置在脚本中的位置。

这行代码出现了运行时错误:

Range(Worksheets("Search Engine").Cells(9, 1), Worksheets("Search Engine").Cells(Endcolumn, Endrow + 2)).Select Selection.RowHeight = 20` when `Endcolumn = 0
4

1 回答 1

4

根据您的评论,Application-defined or object-defined error当您的Endcolumn变量为 0 时,您会看到。发生这种情况是因为 ExcelRange是基于 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
于 2012-07-23T12:54:17.403 回答