According to the description of what you're trying to accomplish and the Google Sheet shared.
You need to break your problem down into several subtasks:
- Selecting all the ranges you'll later need (Players, Dates, Range where you'll write your scores, range where your top scorers will be displayed)
- Adding up each player's goals from all the games to get their total score
- Sorting the players according to their total score
- Create strings to write into your topscorer column
- Write these strings into the topscorer column
My solution is pretty verbose but it seems to work. Please don't hesitate to ask if you have any questions or if clarifications are needed.
function testMe() {
var ID = ''; // ID of your Document
var name = ''; // Name of your sheet
var sourceSheet = SpreadsheetApp.openById(ID); // Selects your Source Spreadsheet by its id
var ssheet = sourceSheet.getSheetByName(name); // Selects your Source Sheet by its name
var scoreRange = ssheet.getRange(2, 3, (sourceSheet.getLastRow() -1), (sourceSheet.getLastColumn() -2)); // Selects the range in which you will enter your scores
var dateRange = ssheet.getRange(2,2,(sourceSheet.getLastRow() -1)); // Selects the range for which player names in row 1
var playerRange = ssheet.getRange(1,3,1,(sourceSheet.getLastColumn() -2)); // selects the range for which dates were entered in column
var topScorerRange = ssheet.getRange(2,1,scoreRange.getNumColumns()); // selects the range where your topscorer output will end up
var numberOfPlayers = playerRange.getNumColumns(); // Gets the number of players you've already entered in row 1
var numberOfGames = playerRange.getNumRows(); // Gets the number of games whose dates you've already entered in Column B
function sortAndUpdateTopScorers() {
var array = scoreRange.getValues();
var totalPlayers = scoreRange.getNumColumns();
var totalGames = scoreRange.getNumRows();
var playerScores = [];
// iterate through the scoreRange and count up each players total score
for (var i = 0; i < totalPlayers; i++) {
var currentPlayer = 0;
for (var j = 0; j < totalGames; j++) {
currentPlayer += array[j][i];
}
playerScores.push([currentPlayer]);
}
// Combine the names of the players and their total score in order to create the strings for your topscorers column
for (var v = 0; v < numberOfPlayers; v++) {
playerScores[v].push(playerRange.getValues()[0][v] + ": " + playerScores[v]);
};
// Sort those strings according to their score
playerScores.sort(function(a,b) {
return b[0]-a[0]
});
// Remove the score value so only the string remains in the array
for (var x = 0; x < playerScores.length; x++) {
playerScores[x].shift();
}
// Write the content of the array into your topscorers column
topScorerRange.setValues(playerScores);
};
sortAndUpdateTopScorers();
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…