在工作表中提示范围以清除文本但保留公式

时间:2018-05-25 12:04:55

标签: google-apps-script google-sheets prompt

我有一个菜单项到"清除表"我想要完成的是弹出提示输入范围的文本,即。" A4:P6"然后脚本将擦除单元格中的任何值,然后将这些单元格中的任何公式粘贴回来。我一直没能找到任何关于这方面的文章,并且已经坚持了一段时间。

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Custom Menu')
      .addItem('Clear Range', 'menuItem1')
      .addSeparator()
      .addSubMenu(ui.createMenu('Email')
          .addItem('Second item', 'menuItem2'))
          .addToUi();
}

function menuItem1() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
       var mySheet = SpreadsheetApp.getActiveSpreadsheet();
       var sheet = mySheet.getSheetByName('Pre op Board');

       var ui = SpreadsheetApp.getUi();

       var result = ui.prompt('What cell to start with?', 
                                        ui.ButtonSet.OK);

       var result2 = ui.prompt('How many cells?', ui.ButtonSet.OK);

       // Process the user's response.
       var button = result.getSelectedButton();
       var cell = result.getResponseText();

       var button2 = result2.getSelectedButton();
       var numCells = result2.getResponseText();

       var cellRange = sheet.getRange(cell); 
       cellRange = cellRange.offset(numCells);
  var values = cellRange.getValues();
  var range = sheet.getRange(cell);
 var formulas = range.getFormulas();
 for (var i in formulas) {
   for (var j in formulas[i]) {
     Logger.log(formulas[i][j]);
     sheet.getRange(cell).clearContent();
 var cell = sheet.getRange(cell);
 cell.setFormulas(formulas);
   }
}}

function menuItem2() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     .alert('You clicked the second menu item!');
}  

1 个答案:

答案 0 :(得分:-1)

请看一下:

// Add menu to the spreadsheet
function onOpen() {
  SpreadsheetApp.getUi()
      .createMenu('Custom Menu')
      .addItem('Show pop-up', 'showPopUp')
      .addToUi();
}

function showPopUp() {
  var ui = SpreadsheetApp.getUi()

  var result = ui.prompt(
      'This is the title of the popup',
      'This is the request (ex. insert range)',
      ui.ButtonSet.OK_CANCEL)  // Delete "_CANCEL" if you don't need the Cancel button

  // Process the user's response
  var text = result.getResponseText()  // Text is the name of the variable you need (string of range defined)
  
  // Feedback on what button was clicked -> Maybe you don't need this part
  var button = result.getSelectedButton()
  if (button == ui.Button.OK) {
    // When "OK" is clicked
    ui.alert('Your range is ' + text + '.')
  } else if (button == ui.Button.CANCEL) {
    // When "Cancel" is clicked
    ui.alert('Cancel pressed')
  } else if (button == ui.Button.CLOSE) {
    // When X in the title bar is clicked
    ui.alert('You closed the dialog')
  }
}

此代码显示询问某些文本的提示。如果您在里面写文字并按“确定”,您将获得带有所需文本的变量“text”。