- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
In Revit I'm getting error : "Revit encounter a Attempt to modify the model outside of transaction."
How to fix the code?
<Transaction(TransactionMode.Manual)>
Public Class CopyRebar
Implements IExternalCommand
Public Function Execute(commandData As ExternalCommandData, ByRef message As String, elements As ElementSet) As Result Implements IExternalCommand.Execute
Dim uiApp As UIApplication = commandData.Application
Dim uidoc As UIDocument = uiApp.ActiveUIDocument
Dim doc As Document = uidoc.Document
' Step 1: Select a bar in Revit model
Dim selectedElement As Element = Nothing
Try
Dim reference As Reference = uidoc.Selection.PickObject(ObjectType.Element, "Select a bar")
selectedElement = doc.GetElement(reference)
Catch ex As Autodesk.Revit.Exceptions.OperationCanceledException
Return Result.Cancelled
End Try
If selectedElement Is Nothing Then
message = "No element selected."
Return Result.Failed
End If
' Step 2: Get the BoundingBox of the selected bar
Dim boundingBox As BoundingBoxXYZ = selectedElement.BoundingBox(doc.ActiveView)
' Step 3: Copy the selected bar
Dim copiedElementIds As New List(Of ElementId)
Dim copiedElementId As ElementId = ElementTransformUtils.CopyElement(doc, selectedElement.Id, New XYZ(0, 0, 0)).First()
copiedElementIds.Add(copiedElementId)
' Step 4: Paste the copied bar “n” times with “s” spacing in X direction into the same host
Dim numberOfCopies As Integer = 5 ' Change the value of n as needed
Dim spacing As Double = 100 ' Change the value of s as needed
Using transaction As New Transaction(doc, "Paste Bars")
transaction.Start()
For i As Integer = 1 To numberOfCopies
Dim copiedId As ElementId = ElementTransformUtils.CopyElement(doc, selectedElement.Id, New XYZ(spacing * i, 0, 0)).First()
copiedElementIds.Add(copiedId)
Next
transaction.Commit()
End Using
' Move the copied elements
For Each id As ElementId In copiedElementIds
Dim element As Element = doc.GetElement(id)
Dim translationVector As New XYZ(100, 0, 0) ' Example translation, adjust as needed
ElementTransformUtils.MoveElement(doc, id, translationVector)
Next
Return Result.Succeeded
End Function
End Class
Solved! Go to Solution.