diff --git a/src/train_gui.cpp b/src/train_gui.cpp
index 4a96056f58..fc4262c89f 100644
--- a/src/train_gui.cpp
+++ b/src/train_gui.cpp
@@ -32,8 +32,13 @@ void CcBuildWagon(Commands, const CommandCost &result, VehicleID new_veh_id, uin
 
 	/* find a locomotive in the depot. */
 	const Vehicle *found = nullptr;
-	for (const Train *t : Train::Iterate()) {
-		if (t->IsFrontEngine() && t->tile == tile && t->IsStoppedInDepot()) {
+	/* The non-deterministic order returned from VehiclesOnTile() does not
+	 * matter here as there must only be one locomotive for anything to happen. */
+	for (const Vehicle *v : VehiclesOnTile(tile)) {
+		if (v->type != VEH_TRAIN) continue;
+
+		const Train *t = Train::From(v);
+		if (t->IsFrontEngine() && t->IsStoppedInDepot()) {
 			if (found != nullptr) return; // must be exactly one.
 			found = t;
 		}