The problem is in this function
;;Check If Deleted and Detach if was Xref
(defun checkIFdeleted (XRefList)
(foreach xr XRefList
(if (vlax-erased-p xr)
(vla-Detach xr)
)
)
(setq XRLi nil)
)
You are testing to see if the block record is erased, not if the inserts are all erased. You will have to make sure that no more inserts reference the block record, then you can detach it. One way is with an ssget call with the name, an other way is to step through all the layouts and see if it exists, or you can get the information from the dxf code of the block record.