如何使用AppendRow?求助实现工作表行逆序复制到另一表
Reverse Rows Using AppendRow Instead of Copy/Paste or Sorting
Hey there! I totally get the disorientation of jumping back into coding after a 5-year break—especially when you're diving into something new like spreadsheet macros. Let's walk through exactly how to use AppendRow to reverse rows from one sheet to another, no copy/paste or sorting required.
Here's a step-by-step solution (using Google Apps Script, since AppendRow is a built-in method there):
- First, we'll grab your source and target sheets from your spreadsheet.
- Then, pull all the data from the source sheet.
- Finally, loop through the source data backwards and use
appendRow()to add each row to the target sheet one by one.
Full Code Example
function reverseRowsWithAppendRow() { // Get the active spreadsheet file const ss = SpreadsheetApp.getActiveSpreadsheet(); // Replace these with your actual sheet names const sourceSheet = ss.getSheetByName("SourceSheet"); const targetSheet = ss.getSheetByName("TargetSheet"); // Fetch all data from the source sheet (includes all rows/columns with content) // If you want to skip a header row, change this to: sourceSheet.getDataRange().getValues().slice(1) const sourceData = sourceSheet.getDataRange().getValues(); // Loop from the LAST row of source data to the FIRST for (let i = sourceData.length - 1; i >= 0; i--) { // Append the current row to the end of the target sheet targetSheet.appendRow(sourceData[i]); } }
Key Notes:
- Skipping Headers: If your source sheet has a header row you don't want included in the reversed data, use
.slice(1)aftergetValues()—this removes the first element (header row) from the data array. - Clearing Target Sheet First: If you want to overwrite the target sheet instead of appending to existing data, add
targetSheet.clearContents();right after definingtargetSheet(just be careful not to erase any important data!). - How
appendRowWorks: This method automatically adds the row to the next empty row at the bottom of the target sheet—no need to calculate row numbers manually.
I hope this gets you up and running smoothly! It's totally normal to feel rusty at first, but breaking problems down into small steps like this makes it way more manageable.
内容的提问来源于stack exchange,提问作者Szymon Wnętrzak
相关产品推荐
相关产品推荐

