2012-07-23 63 views
0

我已經嘗試在錯誤上使用Goto,但即使發生錯誤,它似乎也會跳過此內容,或者即使未發生錯誤,也會執行此操作,具體取決於我將它放在腳本中的位置。在這行代碼發生發生錯誤時是否可以自動保護工作表?

運行時錯誤:

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

你稱之爲「錯誤」是什麼? – ApplePie 2012-07-23 11:13:59

+0

你能提供樣本代碼嗎?那麼,據我所知,我認爲它不能跳過錯誤,因爲在那種情況下,它會錯誤...(?) – Trace 2012-07-23 11:33:53

+0

錯誤,因爲在運行時錯誤,我做了一個搜索引擎,將通過列表的數據並將任何相關數據傳輸到搜索引擎表中,但顯然表格中的數據不應該由用戶改變,但是如果在搜索過程中發生運行時錯誤,它將是可變的。我有一個部分給了我一個ruby錯誤,但我現在已經解決了這個問題,但是對於一個例子,我會把它放在一起 – user1545643 2012-07-23 11:53:51

回答

4

基於您的評論,你看到一個Application-defined or object-defined error當你Endcolumn變量爲0。這是因爲發生了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 
+0

非常感謝,我沒有想到將exit sub放入。出色地工作。 – user1545643 2012-07-23 13:28:11

+0

+1非常好@psubsee – 2013-11-27 13:33:15

相關問題