Sub CreateBlockFromEntities()Dim blockName As StringDim basePoint As VariantDim selectedEntities As AcadSelectionSetDim blockDef As AcadBlockDim blockRef As AcadBlockReference' 设置图块名称blockName = "MyBlock"' 设置图块的基点basePoint = ThisDrawing.Utility.GetPoint(, "请选择图块的基点: ")' 创建选择集On Error Resume NextThisDrawing.SelectionSets("MySelectionSet").DeleteOn Error GoTo 0Set selectedEntities = ThisDrawing.SelectionSets.Add("MySelectionSet")VBA.AppActivate Application.Caption' 提示用户选择图元selectedEntities.SelectOnScreen' 检查是否有图元被选中If selectedEntities.Count = 0 ThenMsgBox "没有选择任何图元。"Exit SubEnd IfDim ents() As AcadEntity, i As LongReDim ents(selectedEntities.Count - 1)For i = 0 To selectedEntities.Count - 1Set ents(i) = selectedEntities.Item(i)Next' 创建图块定义Set blockDef = ThisDrawing.Blocks.Add(basePoint, blockName)' 将选中的图元添加到图块定义中ThisDrawing.CopyObjects ents, blockDef' 插入图块Set blockRef = ThisDrawing.ModelSpace.InsertBlock(basePoint, blockName, 1#, 1#, 1#, 0)' 清理选择集selectedEntities.Delete' 刷新视图ThisDrawing.Regen acAllViewportsMsgBox "图块创建并插入成功!"
End Sub