I wrote practically the same thing several years ago. Some of this code I would do differently today, but this does work. This example was written for a large project where we decided after several hundred sheets were drawn that the door target had to be changed. What it does is make a selection set of all the door targets on the sheet, loop through the set extracting xyz, scale rotation and attributes. Then it deletes the door target and inserts the new one with the same attributes.
It was designed to be called as a subroutine from a larger batch program that loads the sheets one at a time, runs the routine then saves the sheet.
Code:
'================================================================================================
Sub ReplaceBlock()
'================================================================================================
Dim Ipt As Variant
Dim RoomNumber As String
Dim BldgLocation As String
Dim DoorSequence As String
Dim Attrib As Variant
Dim Tag As Variant
Dim Angle As Double
Dim DrTar As AcadBlockReference
Dim BlkRef As AcadBlockReference
Const ScX As Double = 1#
Const ScY As Double = 1#
Const ScZ As Double = 1#
Dim Target As String
Target = "w:\a\blocks\door_tag_oval.dwg"
Dim Sset As AcadSelectionSet
Set Sset = ThisDrawing.SelectionSets.Add("DoorTarget")
Dim Codes() As Integer
ReDim Codes(2)
Dim CodeValues() As Variant
ReDim CodeValues(2)
Codes(1) = 0
Codes(2) = 2
CodeValues(1) = "INSERT"
CodeValues(2) = "door_tag" 'Block name
Sset.Select acSelectionSetAll, , , Codes, CodeValues
If Sset.Count = 0 Then Exit Sub
For Each DrTar In Sset
Ipt = DrTar.InsertionPoint
Ipt(2) = 0#
Angle = DrTar.Rotation
RoomNumber = ""
BldgLocation = ""
DoorSequence = ""
For Each Attrib In DrTar.GetAttributes
With Attrib
Select Case .TagString
Case "RMNO"
RoomNumber = Trim(.TextString)
Case "LO"
BldgLocation = Trim(.TextString)
Case "DS"
DoorSequence = Trim(.TextString)
End Select
End With
Next Attrib
If RoomNumber = "" Then RoomNumber = "----"
If BldgLocation = "" Then BldgLocation = "--"
If DoorSequence = "" Then DoorSequence = "--"
DrTar.Delete
'insert new block here and set attributes
Set BlkRef = ThisDrawing.ModelSpace.InsertBlock(Ipt, Target, ScX, ScY, ScZ, Angle)
For Each Tag In BlkRef.GetAttributes
Select Case Tag.TagString
Case "RMNO"
Tag.TextString = RoomNumber
Case "LO"
Tag.TextString = BldgLocation
Case "DS"
Tag.TextString = DoorSequence
End Select
Next Tag
BlkRef.Update
Print #G, RoomNumber; Chr(9); BldgLocation; Chr(9); DoorSequence; Chr(9); _
Ipt(0); Chr(9); Ipt(1); Chr(9); FileName
Next DrTar
ThisDrawing.PurgeAll
ThisDrawing.PurgeAll
ThisDrawing.SelectionSets("DoorTarget").Delete
End Sub
The redim() statements I learned from the Joe Sutphin book. It's not really neccessary. Just dim the array directly. Also, I was in the habit of setting option base 1. I don't do that anymore. Just remember you are always off by 1.