Formula reload from scratch after restarting computer

214 views
Skip to first unread message

KING KING

unread,
Aug 29, 2025, 5:50:42 AM (9 days ago) Aug 29
to Google Apps Script Community
Dear Experts,

I have a Google Sheets file using Apps Script.
When I restart my computer and open the file again, the values ​​in my formulas are recalculated from the beginning. This makes the data reload very slow.

If I just close the browser and open it again, the spreadsheet shows the results that were previously loaded. If I restart my computer, the data reloads from the beginning and waits quite a long time, about 10-15 minutes.

Is there a way to fix this?
Screenshot 2025-08-29 164302.png

Keith Andersen

unread,
Aug 29, 2025, 9:42:01 AM (9 days ago) Aug 29
to google-apps-sc...@googlegroups.com
Are you using a custom script And applying it in each cell?

Can you give us an example of the script that is running in each cell?



My website: https://sites.google.com/view/klaweb/
Passions: God, Family, Scriptures, Learning, Data Management, Google Sheets + App Script and much more!

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/google-apps-script-community/35864aef-ae13-4eb2-9554-0609e9ac2a94n%40googlegroups.com.

Kildere S Irineu

unread,
Aug 29, 2025, 9:43:40 AM (9 days ago) Aug 29
to google-apps-sc...@googlegroups.com

Olá!

Este é um problema muito comum e frustrante, mas a boa notícia é que tem uma solução clara. A sua análise está correta: o problema não é o seu computador, mas sim como o Planilhas Google lida com certos tipos de fórmulas, especialmente após uma "reinicialização a frio" como reiniciar o computador.

A Causa Raiz: Funções Voláteis e Cache

O problema está em um conceito chamado "funções voláteis". São fórmulas cujo resultado pode mudar sem que você edite diretamente a célula. As principais culpadas são:

  1. Funções de Importação: Qualquer função que busca dados externos, como IMPORTXMLIMPORTRANGEIMPORTHTML, etc.

  2. Funções Personalizadas do Apps Script: Esta é a causa mais provável no seu caso. Se você criou uma função no Apps Script (ex: function PEGAR_DADO_API(url)) e a está usando como uma fórmula em centenas de células, você está criando um problema de desempenho massivo.

Como funciona o cache:

  • Ao fechar e reabrir o navegador: O Google mantém os resultados das suas fórmulas em um "cache" temporário. Quando você reabre a planilha, ele simplesmente mostra os resultados salvos, o que é muito rápido.

  • Ao reiniciar o computador: Essa conexão e o cache são completamente perdidos. Quando você abre a planilha, o Google é forçado a recalcular todas as suas funções voláteis do zero. Se você tem centenas de células chamando uma função do Apps Script, o Google tenta executar centenas de scripts ao mesmo tempo, o que atinge rapidamente as cotas e limites da plataforma, resultando na lentidão extrema (10-15 minutos) que você está vivenciando.


A Solução: Mudar da Estratégia "Puxar" para "Empurrar"

A solução é parar de fazer com que cada célula individualmente "puxe" (pull) os dados através de uma fórmula. Em vez disso, vamos criar um único script centralizado que "empurra" (push) todos os dados para a sua planilha de uma só vez, em intervalos programados.

Os dados se tornarão valores estáticos na sua planilha (texto e números normais), o que fará com que ela carregue instantaneamente. O script será responsável por atualizar esses valores periodicamente.

Passo 1: Remover as Fórmulas das Células

A primeira coisa a fazer é remover a função personalizada que está causando a lentidão das suas células.
Exemplo: Se suas células têm a fórmula =MINHA_FUNCAO(A1), você precisará apagar essa fórmula.

Passo 2: Criar uma Função Central no Apps Script

Vamos criar uma única função no seu editor de scripts que fará o trabalho de todas as fórmulas de uma vez.

Exemplo de Estrutura:

Imagine que sua função personalizada original se chamava MINHA_FUNCAO(parametro). O novo script se parecerá com isto:

JavaScript
/**
 * Esta é a função principal que busca TODOS os dados e os insere na planilha.
 * Ela substitui o uso de fórmulas personalizadas em cada célula.
 */
function atualizarTodosOsDados() {
  const folha = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SuaAba"); // Mude "SuaAba" para o nome da sua planilha
  
  // Exemplo: Pega todos os parâmetros da coluna A, a partir da linha 2
  const intervaloDeParametros = folha.getRange("A2:A" + folha.getLastRow()); 
  const parametros = intervaloDeParametros.getValues();
  
  const resultados = []; // Array para armazenar todos os resultados

  // Loop através de cada parâmetro para buscar os dados
  for (let i = 0; i < parametros.length; i++) {
    let parametroAtual = parametros[i][0];
    
    // Se a célula do parâmetro estiver vazia, pula para a próxima
    if (parametroAtual === "") {
      resultados.push([""]); // Adiciona uma célula vazia ao resultado
      continue;
    }
    
    // --- COLOQUE A LÓGICA DA SUA FUNÇÃO ORIGINAL AQUI ---
    // Exemplo:
    // var url = "https://api.exemplo.com/dados?id=" + parametroAtual;
    // var resposta = UrlFetchApp.fetch(url);
    // var dado = JSON.parse(resposta.getContentText()).valor;
    //
    // Para este exemplo, vamos usar um valor simulado:
    var dado = "Resultado para " + parametroAtual; 
    // ---------------------------------------------------

    // Adiciona o resultado ao array. É importante que seja um array dentro de um array.
    resultados.push([dado]); 
  }
  
  // Escreve TODOS os resultados de volta na planilha de uma só vez (muito eficiente)
  // Exemplo: Escreve os resultados na coluna B, a partir da linha 2
  folha.getRange("B2:B" + (resultados.length + 1)).setValues(resultados);
}

Passo 3: Automatizar a Execução com um Gatilho (Trigger)

Agora, faremos com que este script rode automaticamente, sem que você precise fazer nada.

  1. No editor do Apps Script, clique no ícone de relógio ("Acionadores") no menu à esquerda.

  2. Clique no botão "+ Adicionar acionador" no canto inferior direito.

  3. Configure o gatilho:

    • Função a ser executada: atualizarTodosOsDados

    • Escolha qual implantação deve ser executada: Principal

    • Selecione a origem do evento: Baseado em tempo

    • Selecione o tipo de acionador baseado em tempo: Temporizador de horas (ou de minutos, ou diário, dependendo da sua necessidade).

    • Selecione o intervalo de horas: A cada hora (ou o intervalo que preferir).

  4. Clique em Salvar.

Resumo dos Benefícios da Nova Abordagem

  1. Carregamento Instantâneo: Sua planilha conterá apenas texto e números, não centenas de fórmulas que precisam ser recalculadas. Ela abrirá tão rápido quanto qualquer planilha normal.

  2. Dados Estáveis: Os dados não desaparecerão ou mostrarão "Carregando...". Eles estarão sempre lá.

  3. Atualizações Controladas: Os dados serão atualizados em segundo plano, automaticamente, no intervalo que você definiu, mesmo que a planilha esteja fechada.

  4. Evita Cotas: Em vez de centenas de pequenas execuções de script, você terá uma única execução maior e mais eficiente, que não sobrecarrega o sistema.

Esta é a maneira correta e profissional de lidar com a busca de dados em massa no Planilhas Google e resolverá seu problema de lentidão permanentemente.


--

KING KING

unread,
Aug 31, 2025, 12:51:12 PM (7 days ago) Aug 31
to Google Apps Script Community
Hi Keith Andersen,

Thank you for your helping.

Are you using a custom script And applying it in each cell? -> Yes. I'm using a custom script And applying it in each cell.
Can you give us an example of the script that is running in each cell? -> Please open this for the example. link https://docs.google.com/spreadsheets/d/1ZUfByqocUGEQtlFE3scHlasZRU5pWgcO_YOYWrPb9lo/edit?usp=sharing 

Regards,
David
Message has been deleted

KING KING

unread,
Aug 31, 2025, 12:58:55 PM (7 days ago) Aug 31
to Google Apps Script Community
Obrigado pelo seu feedback.
Aqui está o meu ficheiro e script  https://docs.google.com/spreadsheets/d/1ZUfByqocUGEQtlFE3scHlasZRU5pWgcO_YOYWrPb9lo/edit?usp=sharing . Poderia criar uma folha de cálculo semelhante e ajustá-la para mim? Desculpem o meu português, por isso não consigo entender muito bem.
e note também que não tenho apenas 1 folha de cálculo, mas muitas folhas de cálculo na mesma pasta de trabalho

Keith Andersen

unread,
Sep 2, 2025, 8:03:30 PM (5 days ago) Sep 2
to google-apps-sc...@googlegroups.com
King
Copy this spreadsheet to make your own to run as it is presently view only. Give it permission to run.

This will run countColoredCells() upon opening in under 3 seconds. It also will create a "Special Menu" at the top to run whenever you like.

You may have to first run it in the script editor to get the "Special Menu".

Post back if it is what you were looking for.


--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.


--

Passions: God, Family, Friends, Scripture, Data Management, Google Sheets + App Script, MS Access, Programing, sharing and much more.

KING KING

unread,
Sep 2, 2025, 9:56:12 PM (4 days ago) Sep 2
to Google Apps Script Community
Hi Keith Andersen,

I only have view permission so I can't see your formula or script.
Screenshot 2025-09-03 085415.png

Keith Andersen

unread,
Sep 2, 2025, 10:02:07 PM (4 days ago) Sep 2
to google-apps-sc...@googlegroups.com
You do have Editor permission.

There aren't formulas - it runs a script. Run the script from the editor then you will have a "Special Menu" in the top tool bar to run the script.



KING KING

unread,
Sep 2, 2025, 10:10:12 PM (4 days ago) Sep 2
to Google Apps Script Community
Hi Keith Andersen,

It's working fine for the O column now but it's not working for the P column.
What if I have more columns like this? (maybe 4 or 5 columns)

Keith Andersen

unread,
Sep 2, 2025, 10:16:10 PM (4 days ago) Sep 2
to google-apps-sc...@googlegroups.com
On your original - I made a mistake and replaced your custom codes with my script.  Do you have your custom codes you can replace?


Also - did you test the "copy" i revised with the "Special Menu"?

KING KING

unread,
Sep 2, 2025, 10:23:00 PM (4 days ago) Sep 2
to Google Apps Script Community

Hi Keith Andersen,

Yes, I have sent my custom code to you.
I have tested the Special Menu, it's works as well.

Keith Andersen

unread,
Sep 2, 2025, 10:37:38 PM (4 days ago) Sep 2
to google-apps-sc...@googlegroups.com
Ok, I restored your Book1 back to original. Sorry for mistake.


KING KING

unread,
Sep 2, 2025, 10:45:34 PM (4 days ago) Sep 2
to Google Apps Script Community
No problem ^^
Hope you can help me solve this issue.

Keith Andersen

unread,
Sep 2, 2025, 10:52:00 PM (4 days ago) Sep 2
to google-apps-sc...@googlegroups.com
I am working on a script that will accomodate adding columns of different color refrences. 

Additionally, I am working a better custom function.

Keith Andersen

unread,
Sep 2, 2025, 11:41:07 PM (4 days ago) Sep 2
to google-apps-sc...@googlegroups.com
What are you using the Q column (TRUE/FALSE) to do?

KING KING

unread,
Sep 2, 2025, 11:58:55 PM (4 days ago) Sep 2
to Google Apps Script Community
Hi Keith Andersen,

I use the column Q to refresh the result of a specific row after changing the cell’s color, without having to recalculate all the formulas in the other rows of the sheet. Recalculating the entire sheet is quite slow and affects performance. 
I'm facing an issue where, when I shut down and turn on my laptop device again, the formula reloads from the beginning. This process takes a long time, especially when there are many rows in the sheet and the workbook contains multiple sheets.  

Keith Andersen

unread,
Sep 3, 2025, 7:59:33 AM (4 days ago) Sep 3
to google-apps-sc...@googlegroups.com
Using custom formulas with app script - there is no way to get around the triggering of your formulas when you open your computer. 

App script custom formulas take up an enormous amount of resource time. I would not use custom formulas for more than a handful of cells. 

In your test sheet you had app script formulas. This will cause an enormous amount of time to process the sheet. 

The alternative is in the CopyABC tab. Use. The special menu to run the calculation and it will do so in under 3 - 5 seconds. If you look in the script Editor under my code, you will find the global variables section and it clearly shows which variables to alter depending on the structure of your sheet. You can add new columns to either your data or your color references and simply make the changes in these few variables and it will calculate just fine. 

I tried for many hours to create a custom app script formula that would not take as much time to calculate, but all my efforts and variations still took an enormous amount of time to populate the sheet. 

Wish I had better news for you as I know you want to keep the formula concept. 

I wish you well. If you have any questions on my code connected to the special menu, feel free to reach out. 

Cheers 
Keith 



My website: https://sites.google.com/view/klaweb/
Passions: God, Family, Scriptures, Learning, Data Management, Google Sheets + App Script and much more!

KING KING

unread,
Sep 3, 2025, 10:15:03 AM (4 days ago) Sep 3
to Google Apps Script Community
Hi Keith,

Thanks for your very kind support.
I just copied your sheet into 2 new sheets: CopyAlternateFormula-1 (Sheet1) and CopyAlternateFormula-2 (Sheet2) - and there may be many other similar sheets in this workbook.
Each sheet has a different number of rows and columns. At the bottom of each sheet's data row, I have a formula that calculates the sum of the values ​​for each column (=SUM(O4:O503)). When I select Menu and run this value is returned to 0. How can I keep this formula value?

Regards,
David

Keith Andersen

unread,
Sep 3, 2025, 11:11:06 AM (4 days ago) Sep 3
to google-apps-sc...@googlegroups.com
David,
I will likely be on my computer later this evening. There is a way to have one function serve multiple pages by getting the pages range parameters from helper cells on each page and feed into the function. 

I will make a mock up of this and send it to you. We can tweak it further as needed.

This one function will handle unlimited pages and rows/columns calculating each in just a few seconds.



My website: https://sites.google.com/view/klaweb/
Passions: God, Family, Scriptures, Learning, Data Management, Google Sheets + App Script and much more!

Keith Andersen

unread,
Sep 3, 2025, 11:51:01 PM (3 days ago) Sep 3
to google-apps-sc...@googlegroups.com
I have set up a mock sheet with "Special Menu" to run two functions. It is Copy of Book 1 which you are an editor. This is the link.
https://docs.google.com/spreadsheets/d/1LoyqecQZ0aaHhPRHcwVmYymzn5LwQTeL3Mavgl4l6qA/edit?usp=sharing

Here is a video to explain what it does and how it is set up.
https://youtu.be/ogHIpLyFWZo

Make a copy to make it your own. Reach out if you have any questions.

Keith

KING KING

unread,
Sep 4, 2025, 5:30:29 AM (3 days ago) Sep 4
to Google Apps Script Community
Hi Keith,

This is great you even have an explainer video :)
Can I adjust the target range (e.g., from row 12 to row 511)? I have a formula below (row 512) to calculate the sum (=sum(012:O511), but currently, when I run the menu, the value is set to 0.

Screenshot 2025-09-04 162528.png

Keith Andersen

unread,
Sep 4, 2025, 11:33:06 AM (3 days ago) Sep 4
to google-apps-sc...@googlegroups.com
Yes. But why not put your formula to calculate total at the top?
= SUM(O12:O) and SUM(P12:P)



My website: https://sites.google.com/view/klaweb/
Passions: God, Family, Scriptures, Learning, Data Management, Google Sheets + App Script and much more!

Keith Andersen

unread,
Sep 4, 2025, 7:57:12 PM (3 days ago) Sep 4
to google-apps-sc...@googlegroups.com
I created the totals at the top for you so you won't have to scroll down.
Message has been deleted

KING KING

unread,
Sep 4, 2025, 8:32:09 PM (3 days ago) Sep 4
to Google Apps Script Community
Hi Keith,

Yes! We can put the formula to calculate the total at the top. That's a great idea. I see there are many rows of data below that are unused and showing a value of 0. Can we remove them? Just want to process calculations in the data area (Start row: 12; Finish row: 512; Start col: 3; Finish col: 14 that mean C12:N511).

Screenshot 2025-09-05 072132.png

Thank you so much!
David

Keith Andersen

unread,
Sep 4, 2025, 8:33:42 PM (3 days ago) Sep 4
to google-apps-sc...@googlegroups.com
Yes you can change the parameters of each page to suit your needs. If you add rows however, you'll need to re-adjust the parameters.

On Thu, Sep 4, 2025 at 7:30 PM KING KING <king...@gmail.com> wrote:
Hi Keith,

Yes! We can put the formula to calculate the total at the top. That's a great idea. I see there are many rows of data below that are unused and showing a value of 0. Can we remove them? Just want to process calculations in the data area (Start row: 12; Finish row: 512; Start col: 3; Finish col: 14 that mean C12:N511).

Thank you so much!
David

KING KING

unread,
Sep 4, 2025, 8:42:31 PM (3 days ago) Sep 4
to Google Apps Script Community
Yeap! I see it now! Just change  C12:N to C12:N511 for the target range.
You helped me a lot.

Keith Andersen

unread,
Sep 4, 2025, 8:45:17 PM (3 days ago) Sep 4
to google-apps-sc...@googlegroups.com
Glad to help. any questions / problems just reach out. 

By the way, what part of the globe you reside in? Me, Illinois USA.


KING KING

unread,
Sep 4, 2025, 8:51:09 PM (3 days ago) Sep 4
to Google Apps Script Community
I am in Vietnam. If you travel to this beautiful country, please message me :)
Please help to lock this topic if you have permission.
Thank you once again.

Keith Andersen

unread,
Sep 4, 2025, 8:58:21 PM (3 days ago) Sep 4
to google-apps-sc...@googlegroups.com
You're very welcome. Not quite sure how to "lock" the topic. Usually it's the one that initiated it.

Have a great day.
Cheers
Keith.

Reply all
Reply to author
Forward
0 new messages