Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

Google Apps Script, searching using a date

I've never really coded before, so I'm sorry if this is a basic question/if I can't word this properly. Tried to google on my own but I'm pretty sure I'm searching the wrong terms. So I'm making a Date Entry form in Google Sheets. The Form Sheet is where the form is, and the Data sheet is where the data inputted in the Form will be transferred to once the user hits the save button. Cell B2 in the form sheet is where users will input the date. B2 then gets save in the first column, the rest of the data in the Form will be saved in the same row. My goal is to allow B2 to also be used as a search box. Users can search for that date and the Form will repopulate with all the data in the same row as that date. My rationale is to allow users to edit some data on that date if they realize there were mistakes. Currently, if B2 is not a date (e.g. 1111, wwww) the form repopulates. But if it is a date, the form remains empty.

var SEARCH_COL_IDX = 0;
function Search() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formS = ss.getSheetByName("Form");

var str = formS.getRange("B2").getValue();
var values = ss.getSheetByName("Data").getDataRange().getValues();
for(var i = 0; i < values.length; i++) {
  var row = values[i];
  if(row[SEARCH_COL_IDX] == str) {
                formS.getRange("B6").setValue(row[1]);
                formS.getRange("B7").setValue(row[2]);
                formS.getRange("B8").setValue(row[3]);

The data are all supposed to be numbers, but I made them characters for now because I was making sure the correct cell in Data form is going to the correct cell in the Form sheet and vice versa.

question from:https://stackoverflow.com/questions/65914990/google-apps-script-searching-using-a-date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to check whether two dates are the same, you cannot do that directly with an equality operator. There are several ways to compare this. For example, you could use Date.getTime(), or Date.valueOf().

For example, you could do:

if (row[SEARCH_COL_IDX].getTime() === str.getTime()) {
  // ...
}

Related:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...