# Change active collection

Is there a way to change the "active" collection? I can check witch collection is currently selected with this code:

>>> bpy.context.collection
bpy.data.collections['My Collection']


But I can't change it using this property because is read-only. Is there a way to do that?

EDIT

After some research I found out part of the solution. I can use this code to get and set the active layer collection.

# Get the current active layer collection and store it in x
x = bpy.context.view_layer.active_layer_collection
# Select another layer collection from the outliner,
# then use this code to restore x as active
bpy.context.view_layer.active_layer_collection = x


the new problem is that x is not a Collection object, is a LayerCollection and we can't pass any collection created with the method:

myColl = bpy.data.collections.new('My Collection')


So the refined question is: How to obtain a LayerCollection for a particular Collection to change the Active Collection?

In Blender 2.80, I've had some success with something simpler that previous @johnzero7's solution :

collection = bpy.data.collections.new('My Collection')

# NOTE the use of 'collection.name' to account for potential automatic renaming
layer_collection = bpy.context.view_layer.layer_collection.children[collection.name]
bpy.context.view_layer.active_layer_collection = layer_collection

• It doesn't work for collection that is inside another collection, does it? – cppBeginner Oct 8 '20 at 4:27
• That's possible, this answer does not indeed fit a generic "change active collection" solution, it assumes that you created/linked the collection so there's no need for a full search in all layer tree. – rotoglup Oct 8 '20 at 7:45
• OK, thanks for clarifying. – cppBeginner Oct 8 '20 at 9:07

The only way I could find to obtain the LayerCollection for a particular Collection is to transverse bpy.context.layer_collection looking for the name I want

#Recursivly transverse layer_collection for a particular name
def recurLayerCollection(layerColl, collName):
found = None
if (layerColl.name == collName):
return layerColl
for layer in layerColl.children:
found = recurLayerCollection(layer, collName)
if found:
return found

#Create one collection
myColl = bpy.data.collections.new('My Collection')

#Create another collection
myColl = bpy.data.collections.new('Another Collection')