If you have spaces on multiple phases in the model, then you will need some additional logic to deal with this. The code below assumes that there is only one phase present in the model and that all spaces are on this phase.
I haven't tested the code below but I believe that it should work.
Code:
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.UI;
[Transaction(TransactionMode.Manual)]
public class CreateOneZonePerSpace : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIApplication uiApplication = commandData.Application;
UIDocument uidoc = uiApplication.ActiveUIDocument;
Document doc = uidoc.Document;
Phase firstPhase = doc.Phases.Cast<Phase>().First();
var spaces = new FilteredElementCollector(doc).WherePasses(new SpaceFilter()).Cast<Space>();
using (TransactionGroup transGroup = new TransactionGroup(doc, "Creating Zones from Spaces"))
{
transGroup.Start();
foreach (var space in spaces)
{
string name = space.Name;
using (var trans = new Transaction(doc, "Creating zone for space " + name))
{
trans.Start();
Level spaceLevel = space.Level;
Zone newZone = doc.Create.NewZone(spaceLevel, firstPhase);
SpaceSet spaceSet = new SpaceSet();
spaceSet.Insert(space);
newZone.AddSpaces(spaceSet);
trans.Commit();
}
}
transGroup.Assimilate();
}
return Result.Succeeded;
}
}