AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79555135
Accepted
Jayson Chabot
Jayson Chabot
Asked: 2025-04-04 19:07:36 +0800 CST2025-04-04 19:07:36 +0800 CST 2025-04-04 19:07:36 +0800 CST

Como posso criar identificadores exclusivos?

  • 772

Quando combinei as funções onEdit()

insira a descrição da imagem aqui

Agora me disseram que,

SyntaxError: O identificador 'sheet' já foi declarado linha: 27 arquivo: Code.gs

Por favor, deixe-me saber como eu crio identificadores exclusivos no seguinte Apps Script

function onEdit(e) {

  onEditTimeValue(e);
  const sheet = e.range.getSheet();
  const sheetName = sheet.getName();
  const sheetConfig = { // Configure the sheets and columns should be updated in "Scheduler".
    "Sun": { targetColumn: 4 }, // Column D
    "Mon": { targetColumn: 8 }  // Column H
  };
  if (!(sheetName in sheetConfig)) return; // Only proceed if the edit is in a configured sheet.
  const scheduleSheet = e.source.getSheetByName("Scheduler");
  const range = e.range;
  const column = range.getColumn();
  const row = range.getRow();
  if (row < 3 || (column !== 9 && column !== 13)) return; // Only proceed if the edit is in I3:I or M3:M.
  const nameColumn = column + 1; // Determine the adjacent column.
  const nameCell = sheet.getRange(row, nameColumn).getValue();
  const updatedValue = range.getValue();
  if (!nameCell) return; // Skip if no name is present
  const scheduleNames = scheduleSheet.getRange("A3:A").getValues().flat(); // Get all names from Schedule!A3:A.
  const scheduleRow = scheduleNames.indexOf(nameCell); // Find row number where the name exists in Schedule!A3:A.
  if (scheduleRow === -1) return; // Skip if name not found
  const targetColumn = sheetConfig[sheetName].targetColumn; // Determine target column (based on configuration).
  scheduleSheet.getRange(scheduleRow + 3, targetColumn).setValue(updatedValue); // Update the corresponding column in "Schedule"

  onEditHourValue(e);
  const sheet = e.range.getSheet();
  const sheetName = sheet.getName();
  const sheetConfig = { // Configure the sheets and columns should be updated in "Scheduler".
    "Sun": { targetColumn: 5 }, // Column E
    "Mon": { targetColumn: 9 }  // Column I
  };
  if (!(sheetName in sheetConfig)) return; // Only proceed if the edit is in a configured sheet.
  const scheduleSheet = e.source.getSheetByName("Scheduler");
  const range = e.range;
  const column = range.getColumn();
  const row = range.getRow();
  if (row < 3 || (column !== 12 && column !== 16)) return; // Only proceed if the edit is in L3:L or P3:P.
  const nameColumn = column - 2; // Determine the adjacent column.
  const nameCell = sheet.getRange(row, nameColumn).getValue();
  const updatedValue = range.getValue();
  if (!nameCell) return; // Skip if no name is present
  const scheduleNames = scheduleSheet.getRange("A3:A").getValues().flat(); // Get all names from Schedule!A3:A.
  const scheduleRow = scheduleNames.indexOf(nameCell); // Find row number where the name exists in Schedule!A3:A.
  if (scheduleRow === -1) return; // Skip if name not found
  const targetColumn = sheetConfig[sheetName].targetColumn; // Determine target column (based on configuration).
  scheduleSheet.getRange(scheduleRow + 3, targetColumn).setValue(updatedValue); // Update the corresponding column in "Schedule"
}

Usando a seguinte planilha do Google: POC Scheduler

javascript
  • 1 1 respostas
  • 99 Views

1 respostas

  • Voted
  1. Best Answer
    Wicket
    2025-04-05T04:16:08+08:002025-04-05T04:16:08+08:00

    Sobre a mensagem de erro:

    SyntaxError: O identificador 'sheet' já foi declarado linha: 27 arquivo: Code.gs

    Isso acontece porque na linha 4, o script tem

    const sheet = e.range.getSheet();
    

    Você pode remover a linha 27, mas na próxima vez que executar um script, terá um erro semelhante para a linha 28 atual, e assim por diante para qualquer declaração de variável constque use um nome usado anteriormente na declaração de variável.

    Provavelmente a maneira mais fácil de combinar dois gatilhos de edição é

    1. Altere o nome das duas onEditfunções originais. Certifique-se de atribuir a cada uma delas um nome exclusivo.
    2. Adicione uma nova onEditfunção chamando as duas funções onEdit originais pelos seus novos nomes.

    Pegando o código de uma revisão anterior da sua pergunta, o código resultante deve ficar assim (você ainda deve verificar se ele funciona como esperado):

    function onEdit(e){
    
       onEdit1(e);
       onEdit2(e);  
    }
    
    function onEdit1(e) {
      const sheet = e.range.getSheet();
      const sheetName = sheet.getName();
      const sheetConfig = { // Configure the sheets and columns should be updated in "Scheduler".
        "Sun": { targetColumn: 4 }, // Column D
        "Mon": { targetColumn: 8 }  // Column H
      };
      if (!(sheetName in sheetConfig)) return; // Only proceed if the edit is in a configured sheet.
      const scheduleSheet = e.source.getSheetByName("Scheduler");
      const range = e.range;
      const column = range.getColumn();
      const row = range.getRow();
      if (row < 3 || (column !== 9 && column !== 13)) return; // Only proceed if the edit is in I3:I or M3:M.
      const nameColumn = column + 1; // Determine the adjacent column.
      const nameCell = sheet.getRange(row, nameColumn).getValue();
      const updatedValue = range.getValue();
      if (!nameCell) return; // Skip if no name is present
      const scheduleNames = scheduleSheet.getRange("A3:A").getValues().flat(); // Get all names from Schedule!A3:A.
      const scheduleRow = scheduleNames.indexOf(nameCell); // Find row number where the name exists in Schedule!A3:A.
      if (scheduleRow === -1) return; // Skip if name not found
      const targetColumn = sheetConfig[sheetName].targetColumn; // Determine target column (based on configuration).
      scheduleSheet.getRange(scheduleRow + 3, targetColumn).setValue(updatedValue); // Update the corresponding column in "Schedule"
    }
    
    
    function onEdit2(e) {
      const sheet = e.range.getSheet();
      const sheetName = sheet.getName();
      const sheetConfig = { // Configure the sheets and columns should be updated in "Scheduler".
        "Sun": { targetColumn: 5 }, // Column E
        "Mon": { targetColumn: 9 }  // Column I
      };
      if (!(sheetName in sheetConfig)) return; // Only proceed if the edit is in a configured sheet.
      const scheduleSheet = e.source.getSheetByName("Scheduler");
      const range = e.range;
      const column = range.getColumn();
      const row = range.getRow();
      if (row < 3 || (column !== 12 && column !== 16)) return; // Only proceed if the edit is in L3:L or P3:P.
      const nameColumn = column - 2; // Determine the adjacent column.
      const nameCell = sheet.getRange(row, nameColumn).getValue();
      const updatedValue = range.getValue();
      if (!nameCell) return; // Skip if no name is present
      const scheduleNames = scheduleSheet.getRange("A3:A").getValues().flat(); // Get all names from Schedule!A3:A.
      const scheduleRow = scheduleNames.indexOf(nameCell); // Find row number where the name exists in Schedule!A3:A.
      if (scheduleRow === -1) return; // Skip if name not found
      const targetColumn = sheetConfig[sheetName].targetColumn; // Determine target column (based on configuration).
      scheduleSheet.getRange(scheduleRow + 3, targetColumn).setValue(updatedValue); // Update the corresponding column in "Schedule"
    }
    

    Relacionado

    • Mesclar ou combinar duas funções de gatilho onEdit
    • Ajuste a função onEdit() para coletar resultados em uma guia (em vez de guias separadas)
    • 0

relate perguntas

  • classificação de mesclagem não está funcionando - código Javascript: não é possível encontrar o erro mesmo após a depuração

  • método select.remove() funciona estranho [fechado]

  • Sempre um 401 res em useOpenWeather () - react-open-weather lib [duplicado]

  • O elemento de entrada não possui atributo somente leitura, mas os campos ainda não podem ser editados [fechado]

  • Como editar o raio do primeiro nó de um RadialTree D3.js?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve