If Error(Sheets(ws_str)) = True Then Exit Sub
返回運行時錯誤9. 我知道此工作表不存在。如果在工作表不存在的情況下如何進行錯誤處理?表單不存在時的錯誤處理
If Error(Sheets(ws_str)) = True Then Exit Sub
返回運行時錯誤9. 我知道此工作表不存在。如果在工作表不存在的情況下如何進行錯誤處理?表單不存在時的錯誤處理
嘗試小片的下面的代碼:
Option Explicit
Sub SheetExits()
Dim ws As Worksheet
Dim ws_str As String
ws_str = "aaa" ' for test
On Error Resume Next
Set ws = Worksheets(ws_str)
On Error GoTo 0
If ws Is Nothing Then Exit Sub
End Sub
這將解決你的問題:
Sub ErrorHandling()
On Error GoTo ExitSub
Dim ws As Worksheet
Set ws = Worksheets("NonExistingSheet") 'it will throw an error
MsgBox ("This won't be displayed")
ExitSub:
End Sub
基本上,一開始定義,你的代碼應該在錯誤的情況下恢復。爲了滿足您的要求,請將恢復點設置在End Sub
之前,以便在發生錯誤時直接進入。
Function SheetExists(sheetname as string) as boolean
On error goto whoops
dim ws as worksheet
set ws = worksheets(sheetname)
set ws = nothing
sheetexists = true
exit function
whoops:
sheetexists = false
end function
您可以使用給定的答案來創建** UDF **(用戶定義函數)並將工作表作爲輸入。 – danieltakeshi
[Test or check if sheet exists](https://stackoverflow.com/questions/6688131/test-or-check-if-sheet-exists)可能存在重複 – Indent