In nature species richness and composition, as well as the functioning of individual species, all covary along environmental gradients, making it difficult to tease apart their effects on ecosystem function. Here we use a novel extension of the Price equation to partition the causes of functional variation between any two sites sharing at least one species in common. We use the extension to separate effects of species loss from those of species gain; species gain is analogous to migration in evolution. Previous theoretical and empirical studies of biodiversity and ecosystem function fail to distinguish effects of species gain from those of species loss, and so are conceptually incomplete. Application of this approach to data on total plant biomass along an experimental N enrichment gradient leads to novel empirical insights and reveals subtle effects. For instance, effects of species gain are non-negligible even though enrichment leads to loss of many species and gain of few, and non-random gain of high-biomass species reduces the biomass of the persisting species. We also discuss the interpretation of this new approach, which provides a highly-general partitioning of the factors affecting ecosystem function.