PDA

View Full Version : VBA Error When ran Twice



nlee
2007-11-05, 07:56 PM
All I am having a little trouble when i run this code twice. Any ideas? I am VERY new to programming so it could be something simple i dont know, its the first code I have written so be gentle!

bweir
2007-11-09, 05:16 AM
Judging by the error message I'm guessing that you are trying to set the current layer to one that has been erased. Word of advise, put your code into a Try... Catch statement. It will help with trapping the error and ensure that the Transaction is Disposed of at the end.

Just off the top of my head...


Dim Dwg As Autodesk.AutoCAD.Application.Document = Autodesk.AutoCAD.Application.DocumentManager.MdiActiveDocument
Dim Trans as Autodesk.AutoCAD.DatabaseServices.Transaction = Dwg.Database.TransactionManager.StartTransaction

Try
' Code to create block...

Trans.Commit
Catch ex As Autodesk.AutoCAD.Runtime.Exception
' The next line is nice to display a some what friendly looking message to the user if something goes wrong. Not sure if I got the method name right I don't have my VS on this machine.
Autodesk.AutoCAD.Appliction.ShowAlertMessage(ex.ToString)
' If some thing went wrong abort the transaction.
Trans.Abort
Finally
' Dispose of the transaction and free the memory/resources.
Trans.Dispose
End Try

bweir
2007-11-09, 08:10 PM
I looked at your code today. An error could occur the second time around because you are trying to add a layer with a name that already exists. The first execution will work fine probably because the layer "SqTopSlots" does not yet exist. On the second execution the layer exists but you try to create it anyways. You should make your code more robust and check for / catch errors like this.