VBA と VB のエラー処理は、On Error ステートメントを使用して行います。VB.NET の場合、On Error ステートメントを問題なく使用できますが、Try ステートメントを代わりに使用することをお勧めします。Try ステートメントは On Error Resume Next ステートメントや On Error GoTo Label ステートメントよりも柔軟です。
On Error Resume Next ステートメントと On Error GoTo Label ステートメントは Try-Catch ステートメントを使用して書き直すことができます。次に、Try-Catch を使用して On Error GoTo Label ステートメントを書き換える方法について説明します。
Sub ColorEntities()
On Error GoTo MyErrorHandler
Dim entry As Object
For Each entry In ThisDrawing.ModelSpace
entry.color = acRed
Next entry
' Important! Exit the subroutine before the error handler
Exit Sub
MyErrorHandler:
MsgBox entry.EntityName + " is on a locked layer." + _
" The handle is: " + entry.Handle
Resume Next
End Sub
<CommandMethod("ColorEntities")> _
Public Sub ColorEntities()
'' Get the current document and database, and start a transaction
Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument
Dim acCurDb As Database = acDoc.Database
Using acTrans As Transaction = acCurDb.TransactionManager.StartTransaction()
'' Open the Block table record for read
Dim acBlkTbl As BlockTable
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, _
OpenMode.ForRead)
'' Open the Block table record Model space for read
Dim acBlkTblRec As BlockTableRecord
acBlkTblRec = acTrans.GetObject(acBlkTbl(BlockTableRecord.ModelSpace), _
OpenMode.ForRead)
Dim acObjId As ObjectId
'' Step through each object in Model space
For Each acObjId In acBlkTblRec
Try
Dim acEnt As Entity
acEnt = acTrans.GetObject(acObjId, _
OpenMode.ForWrite)
acEnt.ColorIndex = 1
Catch
Application.ShowAlertDialog(acObjId.ObjectClass.DxfName & _
" is on a locked layer." & _
" The handle is: " & acObjId.Handle.ToString())
End Try
Next
acTrans.Commit()
End Using
End Sub