简体   繁体   English

将单元格值复制到另一个工作表以匹配值

[英]Copy cell value to another sheet for matching value

I have a spreadsheet with two sheets: "Data Base" and "Adendas".我有一个包含两张表的电子表格:“数据库”和“Adendas”。 One has changes records and the other works as a database.一个具有更改记录,另一个用作数据库。

"Data Base" has these columns among others: “数据库”除其他外有这些列:

  • Name (Column D)姓名(D 栏)
  • Location (Column K)位置(K 列)
  • Hours (Column L)小时(L 栏)
  • Vehicle (Column M)车辆(M 栏)

"Adendas" has: “Adendas”有:

  • Name (Column D)姓名(D 栏)
  • Change Type (Column M)更改类型(M 列)
  • Location (Column N)位置(N 列)
  • Hours (Column O)小时(O 栏)
  • Vehicle (Column P)车辆(P 栏)
  • From (Column Q)来自(Q 列)
  • Change Confirmation (Column R)更改确认(R 列)

Observations:观察:

Changes are added to the 'Adendas' sheet with a from date specified.更改将添加到“Adendas”工作表,并指定起始日期。 When the date matches today, it is supposed to copy the correspondent information depending the type of change from 'Adendas' to the matching name in 'Data Base'当日期与今天匹配时,应该根据从“Adendas”到“数据库”中匹配名称的更改类型复制相应的信息

  • The Data Base sheet look like this:数据库表如下所示:

数据库表

  • Adendas Sheet:附录表:

附录表

For example, today 04/25/2022, it should move the vehicle information from Column P in Adendas to Column M in Data Base for Name2 and then apply a true value to the Confirmation box in Adenda's Column R例如,今天 04/25/2022,它应该将车辆信息从 Adendas 中的P 列移动到Name2的数据库中的M 列,然后将真值应用于 Adenda 的列 R中的确认框

Result should look like this:结果应如下所示:

Data Base数据库结果Adendas附录结果2

After lot of search and investigation, I managed to create the following code which works for the date and checkbox part but I can't manage to apply the change to the matching name value as it should since it's copying it but at a random cell.经过大量搜索和调查,我设法创建了以下适用于日期和复选框部分的代码,但我无法设法将更改应用于匹配的名称值,因为它是在随机单元格中复制它。

function parse_worker(employee) {
    /* Given a row from the spreadsheet, parse the data into a javascript object. */

    if (typeof(employee) == 'undefined') {
      return null;
    }

    let trabajador = {};

    trabajador.nombre = employee[3];
    trabajador.tipo = employee[12];
    trabajador.location = employee[13];
    trabajador.hours = employee[14];
    trabajador.vehicle = employee[15];
    trabajador.fecha = employee[16];
    trabajador.cambio = employee[17];

    return trabajador;
};

function are_dates_equal(date1, date2) {
    /* Returns true if the two dates are equal, false otherwise. 
    
    It only compares the day, the month and the year. Time is not considered.
    */

    return date1.getUTCDate() == date2.getUTCDate() && date1.getUTCMonth() == date2.getUTCMonth() && date1.getUTCFullYear() == date2.getUTCFullYear();
}

function try_to_copy_data() {
    /* Iterate over the rows in the spreadsheet and make the corresponding change if it's time to do it. */

    var app = SpreadsheetApp;
    var spreadsheet = app.getActiveSpreadsheet();
    var sourceSheet = spreadsheet.getSheetByName('Adendas');
    var sourceRows = sourceSheet.getRange(2, 1, sourceSheet.getLastRow() - 1, sourceSheet.getLastColumn()).getValues();
    var targetSheet = spreadsheet.getSheetByName('Data Base');
    var targetRows = targetSheet.getRange(2, 1, targetSheet.getLastRow() - 1, targetSheet.getLastColumn()).getValues();


    sourceRows.forEach(function(row, i) {
        /* Copy's the data to the given employee if it's time to do it and the change type matches. */

        // Exit the function if the employee has no date.
        let is_date_set = row[16] !== '';
        if (!is_date_set) {
            return;
        }

        let worker = parse_worker(row);
        var now = new Date();

        Logger.log(now.toLocaleDateString('es-ES', {timeZone: 'UTC'}));
        Logger.log(worker.fecha.toLocaleDateString('es-ES', {timeZone: 'UTC'}));

        // Exit the function if is not time to make the change
        if (!are_dates_equal(now, worker.fecha)) {
            return;
        }

        // Exit the function if change has already made
        if (worker.cambio === true) {
            return;
        }

        if (are_dates_equal(now, worker.fecha) && worker.tipo === "Vehículo"){
            targetSheet.getRange(i+2,[13]).setValue(worker.vehicle);
            sourceSheet.getRange(i+2,[18]).setValue(true);
        } else if (are_dates_equal(now, worker.fecha) && worker.tipo === "Centro de Trabajo"){
            targetSheet.getRange(i+2,[11]).setValue(worker.vehicle);
            sourceSheet.getRange(i+2,[18]).setValue(true);
        } else if (are_dates_equal(now, worker.fecha) && worker.tipo === "Horas Contrato"){
            targetSheet.getRange(i+2,[12]).setValue(worker.vehicle);
            sourceSheet.getRange(i+2,[18]).setValue(true);
        } else {
            Logger.log("Error! Not a valid change.");
        }

    })
}
try_to_copy_data();

The idea was to use the general knowledge on how to copy the value automatically and then adapt it to the positioning thing but I'm not even close to figure out how to do it.我的想法是使用关于如何自动复制值然后使其适应定位的一般知识,但我什至还没有弄清楚如何去做。

EDIT: Final working code thanks to Yuri's help编辑:感谢 Yuri 的帮助,最终的工作代码

function parse_worker(employee) {
    /* Given a row from the spreadsheet, parse the data into a javascript object. */

    if (typeof(employee) == 'undefined') {
      return null;
    }

    let trabajador = {};

    trabajador.nombre = employee[3];
    trabajador.tipo = employee[12];
    trabajador.location = employee[13];
    trabajador.hours = employee[14];
    trabajador.vehicle = employee[15];
    trabajador.fecha = employee[16];
    trabajador.cambio = employee[17];

    return trabajador;
};

function are_dates_equal(date1, date2) {
    /* Returns true if the two dates are equal, false otherwise. 
    
    It only compares the day, the month and the year. Time is not considered.
    */

    return date1.getUTCDate() == date2.getUTCDate() && date1.getUTCMonth() == date2.getUTCMonth() && date1.getUTCFullYear() == date2.getUTCFullYear();
}

function try_to_copy_data() {
    /* Iterate over the rows in the spreadsheet and make the corresponding change if it's time to do it. */

    var app = SpreadsheetApp;
    var spreadsheet = app.getActiveSpreadsheet();
    var sourceSheet = spreadsheet.getSheetByName('Adendas');
    var sourceRows = sourceSheet.getRange(2, 1, sourceSheet.getLastRow() - 1, sourceSheet.getLastColumn()).getValues();
    var targetSheet = spreadsheet.getSheetByName('Data Base');
    var targetRows = targetSheet.getRange(2, 1, targetSheet.getLastRow() - 1, targetSheet.getLastColumn()).getValues();
    var targetNames = targetRows.map(e => e[3]);



    sourceRows.forEach(function(row, i) {
        /* Copy's the data to the given employee if it's time to do it and the change type matches. */

        // Exit the function if the employee has no date.
        let is_date_set = row[16] !== '';
        if (!is_date_set) {
            return;
        }

        let worker = parse_worker(row);
        var now = new Date();
        var row_index = targetNames.indexOf(worker.nombre);


        Logger.log(now.toLocaleDateString('es-ES', {timeZone: 'UTC'}));
        Logger.log(worker.fecha.toLocaleDateString('es-ES', {timeZone: 'UTC'}));

        // Exit the function if is not time to make the change
        if (!are_dates_equal(now, worker.fecha)) {
            return;
        }

        // Exit the function if change has already made
        if (worker.cambio === true) {
            return;
        }

        if (are_dates_equal(now, worker.fecha) && worker.tipo === "Vehículo"){
            targetSheet.getRange(row_index+2,13).setValue(worker.vehicle);
            sourceSheet.getRange(i+2,[18]).setValue(true);
        } else if (are_dates_equal(now, worker.fecha) && worker.tipo === "Centro de Trabajo"){
            targetSheet.getRange(row_index+2,11).setValue(worker.location);
            sourceSheet.getRange(i+2,[18]).setValue(true);
        } else if (are_dates_equal(now, worker.fecha) && worker.tipo === "Horas Contrato"){
            targetSheet.getRange(row_index+2,12).setValue(worker.hours);
            sourceSheet.getRange(i+2,[18]).setValue(true);
        } else {
            Logger.log("Error! Not a valid change.");
        }

    })
}
try_to_copy_data();

Probably it should be something like this:大概应该是这样的:

function try_to_copy_data() {

  var now = new Date();

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = ss.getSheetByName('Adendas');
  var sourceRows = sourceSheet.getDataRange().getValues().slice(1);
  var targetSheet = ss.getSheetByName('Data Base');
  var [header, ...targetRows] = targetSheet.getDataRange().getValues();
  var targetNames = targetRows.map(e => e[3]);

  sourceRows.forEach((row, i) => {

    let worker = parse_worker(row);
    if (worker.ok == true) return;
    if (!are_dates_equal(now, worker.date)) return;

    var row_index = targetNames.indexOf(worker.name);

    if (worker.location != '') targetRows[row_index][10] = worker.location;
    if (worker.hours != '')    targetRows[row_index][11] = worker.hours;
    if (worker.vehicle != '')  targetRows[row_index][12] = worker.vehicle;

    sourceSheet.getRange('R' + (i+2)).check();
  })

  var table = [header, ...targetRows];
  targetSheet.clearContents()
    .getRange(1, 1, table.length, table[0].length)
    .setValues(table);
}

function parse_worker(row) {
  let worker = {
    name:     row[3],
    type:     row[12],
    location: row[13],
    hours:    row[14],
    vehicle:  row[15],
    date:     row[16],
    ok:       row[17],
  }
  return worker;
}

function are_dates_equal(date1, date2) {
  return date1.getUTCDate() == date2.getUTCDate() &&
    date1.getUTCMonth() == date2.getUTCMonth() &&
    date1.getUTCFullYear() == date2.getUTCFullYear();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在编辑时将动态单元格的值复制到另一个工作表 - Copy value of a dynamic cell to another sheet on edit 根据单元格值将行从一张纸复制到另一张纸 - Copy row from one sheet to another base on cell value Google Apps脚本:将单元格值复制到另一个工作表中,条件是要复制并放置该值 - Google Apps Script: Copy cell value to another sheet with condition to copy and position the value Google表格:根据单元格值将一行数据移动到另一张表格 - Google Sheets: Move a row of data to another sheet based on cell value 根据特定的键值将数据从一张纸复制到另一张纸 - Copy data from one sheet to another based on a specific key value Google Script:根据值将行从一张纸复制到另一张纸 - Google Script: Copy row from one sheet to another depending on value GAS Google Script - 如何复制值并粘贴到另一个单元格 - GAS Google Script - How copy value and paste in another Cell 如何从谷歌电子表格动态设置值到另一个谷歌电子表格单元格 - How to set dynamically value from a google spread sheet to another google spread sheet cell 将工作表复制到新电子表格,将单元格值添加到新电子表格名称的末尾 - Copy sheet to new spreadsheet, Add cell value to end of new spreadsheet name 根据列中单元格的值,将范围从一张纸复制/粘贴到其他几张 - Copy/paste a range from one sheet to several others depending on the value of a cell in a column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM