Home > database >  Why do I get an 'Object is referenced' error when deleting a block by name?
Why do I get an 'Object is referenced' error when deleting a block by name?

Time:01-31

I'm creating some lines dynamically from an Excel file. I want to delete them programmatically; I created them as a block with a custom name (I don't know! Maybe there is another way).

Now, I want to delete a block by name:

Dim Blk As AcadBlock
Set Blk = ThisDrawing.Blocks("1|3137.34101634953|22059.6018301436|13369.4589738571|18917.7435065279||line")
Blk.Delete

But I got this error:

Object is referenced

enter image description here

this is my function to create line as block:

Function CreateLineBlock(firstPoint, secondPoint, bname)

    Dim StartPoint(0 To 2) As Double, insPt(0 To 2) As Double
    Dim MyBlock As AcadBlock
    Dim EndPoint(0 To 2) As Double
    Dim BlockName As String
    BlockName = bname & "|line"
    
    
    StartPoint(0) = firstPoint(0)
    StartPoint(1) = firstPoint(1)
    'StartPoint(2) = 0
    
    EndPoint(0) = secondPoint(0)
    EndPoint(1) = secondPoint(1)
    'EndPoint(2) = 0

    'With ThisDrawing.ModelSpace
    '.AddLine StartPoint, EndPoint
    '.Item(.Count - 1).Update
    'End With
    'Create a new block
     Set MyBlock = ThisDrawing.Blocks.Add(insPt, BlockName)

    'ADD LINES DIRECT ON YOUR BLOCK
    MyBlock.AddLine StartPoint, EndPoint

    'Add the blockreference in model space
    ThisDrawing.ModelSpace.InsertBlock insPt, BlockName, 1, 1, 1, 0
End Function

How can I delete this block?

CodePudding user response:

Per the method demonstrated by my Delete Blocks function, you'll first need to delete all references of the block definition from all containers (i.e. all other block definitions and layouts) before the block definition of the target block can be deleted.

In VBA, this might looks something like this:

Function DelBlock(strBnm As String)
    Dim objDef As AcadBlock
    Dim objCmp As AcadObject
    
    For Each objDef In ThisDrawing.Blocks
        If Not objDef.IsXRef Then
            For Each objCmp In objDef
                If objCmp.ObjectName = "AcDbBlockReference" Then
                    If objCmp.Name = strBnm Then
                        objCmp.Delete
                    End If
                End If
            Next objCmp
        End If
    Next objDef
    
    ThisDrawing.Blocks(strBnm).Delete
End Function
  • Related