Select elements by filtered Workset PYTHON

I got an error in this script, any idea why?
"import clr
clr.AddReference(‘RevitAPI’)
clr.AddReference(‘RevitServices’)
clr.AddReference(‘RevitNodes’)
clr.AddReference(‘RevitAPIUI’)

from Autodesk.Revit.DB import FilteredElementCollector, Workset, ElementId
from Autodesk.Revit.UI import TaskDialog
from RevitServices.Persistence import DocumentManager
from System.Collections.Generic import List

Get the current document and UIDocument

doc = DocumentManager.Instance.CurrentDBDocument
uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument

Input: List of Workset names from Dynamo

workset_names = IN[0] # Expected: list of strings [“PH2_STR_Steel”, “PH1_STR_Steel”]

Validate input

if not isinstance(workset_names, list):
workset_names = [workset_names]

Retrieve the Worksets by name

worksets = FilteredElementCollector(doc).OfClass(Workset).ToElements()
workset_ids =
for ws in worksets:
if ws.Name in workset_names:
workset_ids.append(ws.Id)

Collect all model elements (not types)

elements_in_doc = FilteredElementCollector(doc).WhereElementIsNotElementType().ToElements()

Filter elements by WorksetId

filtered_elements =
for elem in elements_in_doc:
try:
if elem.WorksetId in workset_ids:
filtered_elements.append(elem)
except:
continue # Skip elements without WorksetId

Select filtered elements

message = “”
if filtered_elements:
try:
ids = List[ElementId]([elem.Id for elem in filtered_elements])
uidoc.Selection.SetElementIds(ids)
message = “Selected {} elements from the specified worksets.”.format(len(filtered_elements))
except Exception as e:
message = "Error during selection: " + str(e)
else:
message = “No elements found in the specified worksets.”

Output

OUT = [filtered_elements, message]

Select elements.txt (1.8 KB)

the error message explains itself: indentation

1 Like

I adjust the code but still not working
Select elements_2.txt (1.8 KB)


wait, this is not how worksets are collected.

Worksets cannot be acquired via a filtered element collector, but are instead accessed via a FilteredWorksetCollector. You’ll need to adjust the code accordingly - the API documentation shows how to do so pretty explicitly so you can refer to that for ‘how’.

FilteredWorksetCollector(doc).WherePasses(WorksetKindFilter(WorksetKind.UserWorkset)).ToWorksets()

3 Likes

I got it work, thanks
Select elements_3.txt (1.9 KB)

I learned something new today. This is awesome!!!

1 Like