Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. Problem getting sheet1 - Exception: You do not have permission to perform that action. (line 31).
  2.  
  3. /* =copyColumns("MyDataSheet!C,A,W",8) */
  4.  
  5. function copyColumns(sourceRange,start,sheetKey) {
  6. // Initialize optional parameter
  7. if(!sheetKey && typeof start!== "number") {
  8. sheetKey = start;
  9. start = 1;
  10. } else {
  11. start = start || 1;
  12. }
  13. // Check SourceRange Input
  14. var inputRe = /^((.*?!)(?=[a-z],?|[a-i][a-z]))?[a-i]?[a-z](,[a-i]?[a-z])*$/i;
  15. if(!inputRe.test(sourceRange))
  16. throw "Invalid SourceRange: " + sourceRange;
  17.  
  18. // Check Start Row
  19. if(typeof start !== "number")
  20. throw "Starting row must be a number! Got: " + start;
  21. if(start % 1 !== 0)
  22. throw "Starting row must be an integer! Got: " + start;
  23. if(start < 1)
  24. throw "Starting row can't be less than 1! Got: " + start;
  25.  
  26. // Get the Source Sheet
  27. try {
  28. var ss = sheetKey
  29. ? SpreadsheetApp.openById(sheetKey)
  30. : SpreadsheetApp.getActiveSpreadsheet();
  31. } catch(err) {
  32. throw "Problem getting sheet" + sheetKey + " - " + err;
  33. }
  34. var sheetName = sourceRange.match(/^.*?(?=!)/);
  35. var sheet = sheetName
  36. ? ss.getSheetByName(sheetName[0])
  37. : ss.getActiveSheet();
  38.  
  39. // Check that everything is still valid
  40. if(!sheet)
  41. throw "Could not find sheet with name: " + sheetName;
  42. if(start > sheet.getLastRow())
  43. throw "No data beyond row: " + start + " Last row: " + sheet.getLastRow();
  44.  
  45. // Get the values
  46. var lastCol = sheet.getLastColumn();
  47. var lastRow = sheet.getLastRow()-start+1;
  48. var values = sheet.getRange(start,1,lastRow,lastCol).getValues();
  49.  
  50. // Get the desired columns from the string
  51. var desiredColMatch = sourceRange.match(/([a-i]?[a-z](,[a-i]?[a-z])*)$/i);
  52. var desiredColumns = desiredColMatch[0].toUpperCase().split(",");
  53.  
  54. // In case the column we are trying to grab doesn't exist in the sheet
  55. var lastColId = sheet.getMaxColumns() - 1; // Array is 0 indexed, Sheet is 1
  56.  
  57. // Get the numerical values of the passed in Column Ids
  58. var columns = desiredColumns.map(function(colId){
  59. var num = colId.length - 1; // 0 or 1
  60. var colNum = colId.charCodeAt(num)-65+num*26*(colId.charCodeAt(0)-64);
  61. if(colNum > lastColId)
  62. throw "Invalid Column: " + colId + " - Column not in: " + sheetName;
  63. return colNum;
  64. });
  65.  
  66. //Map the values to a new array of just the columns we want
  67. return values.map(function(row){
  68. return columns.map(function(col){
  69. return row[col]
  70. })
  71. });
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement