Гугл таблица триггер по дате как поставить
Перейти к содержимому

Гугл таблица триггер по дате как поставить

  • автор:

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 80271d8fabab01f3 • Your IP: Click to reveal 86.107.21.84 • Performance & security by Cloudflare

Как настроить подставление текущей даты, при заполнении соседней ячейки?

Добрый день.
Есть таблица, в нее вводятся данные и нужно чтобы было отслеживание по вводу. В силу некоторых обстоятельств, формы не выход.
Была написана формула:
=IF(D201=»акт»;»=now()»;»wait»)
Формула проверяет, если в ячейке D201 имеется слово акт, то подставляется формула =now(). Проблема в том, что формула вставляется в ячейку как текст. Как сделать чтобы она выполнялась?

  • Вопрос задан более трёх лет назад
  • 41728 просмотров

Оценить 1 комментарий

  • Facebook
  • Вконтакте
  • Twitter

Большое спасибо!
Подскажите, пожалуйста, верный скрип, если время не важно, то есть оставить только дату.

Буду очень благодарна!

Kalaganov5

Google docs Скрипт автоматического заполнения ячеек

Ниже представлен скрипт автоматического заполнения ячеек первого и второго столбца датой и временем, при изменении ячейки из третьего столбца.
Работает скрипт так:
если обнаружена правка в документе,
проверяем, изменена ли ячейка из третьего столбца и это изменение произведено на листе с названием «Лист1», если да,
проверяем, не пустая ли ячейка из первого столбца (если не пустая, значит дата была уже ранее проставлена, соответственно время и дату не меняем).
если пуста, то
в ячейку первого столбца добавляем дату в формате: год.месяц.день
в ячейку второго столбца добавляем время GMT+03 в формате: час:минуты

Следим за балансом «Яндекс.Директа» в «Google Таблицах»

Мы очень любим микро автоматизацию PPC проектов в Google Таблицах.

В одной из прошлых статей мы сделали формулу с помощью которой можно получить статистику из Яндекс Директа не покидая Google Таблиц. Инструмент оказался полезным. Им воспользовалось более 1000 пользователей.

В комментариях, на почту и в личных сообщениях мы получили вопросы о возможности получения баланса.

В этом материале расскажем, как получить баланс аккаунта Яндекс Директ формулой в Google Таблицах и отправлять уведомления об остатке по расписанию на почту

Из Яндекс Директа можно получить данные при помощи API. Это касается как статистики так и другой информации.

В данной таблице уже есть формула YandexDirectBalance. Этой формулой можно получить баланс из агентского или клиентского аккаунта Яндекс Директ.

Делается это так:

Вызываете формулу YandexDirectBalance

Первым аргументом указываете токен. Получить его можно в нашем приложении Яндекс OAuth

Вторым аргументом указываете логин аккаунта Яндекс Директ.

Можно указать несколько логинов. Перечислите их через точку запятую:

Формула вернёт таблицу из 3 столбцов: логин, баланс, валюта.

Но значение баланса в ячейке таблицы несет не так много пользы.

В этом материале мы предложим способ отслеживания баланса с отправкой уведомления на почту по расписанию. И все это в Google Таблицах

Представим, что мы хотим получать уведомление, когда денег на балансе осталось на 7 или менее дней.

В таблице «Баланс Яндекс.Директ» есть лист – schedule. В этом листе необходимо указать все параметры для получения баланса.

Параметры отмеченные знаком ✅ – можно редактировать, �� – нельзя редактировать.

Имя — название клиента (произвольное имя)

Токен — токен агентского или клиентского аккаунта

Логин — логин аккаунта

Баланс — выводится баланс формулой YandexDirectBalance

Расход за дней — кол-во дней для получения статистики расходов в столбце «Расход». Пример: 7 дней, это значит: если сегодня 8 августа, то период с 1 августа по 7 августа.

Расход — затраты за указанное кол-во дней

Дней открута — фактическое кол-во дней расхода. Например по Клиенту-1 получили 7 дней, а по Клиенту-2 получили 6 дней. Это значит, что по клиенту 2 в один из дней кампании были на стопе

Средний расход — результат «Расхода», деленное на «Дней открута»

Тема сообщения — тема письма, которое придет на почту.

К примеру, можно написать формулу:

Результат : Уведомление о балансе по клиенту Клиент-1

Сообщение — текст письма, которое приходит на почту.

Результат : Уважаемый Клиент-1! Ваш баланс 333730,04. Он закончится через 4 дня. Примите меры!

Email — адреса для отправки необходимо заполнить через точку с запятой. Также аналогично другим столбцам можно выстроить свою логику отправок с помощью базовых формул Google-таблиц.

К примеру: нам необходимо отправлять уведомление только в том случае, если денег в кабинете будет меньше, чем наш расход за неделю. В таком случае формула будет выглядеть так:

В данной формуле мы говорим: если баланс / средний расход в день меньше чем 7 дней, то показать список электронных адресов, если нет — не показывать. В таком случае, когда денег на балансе хватит больше чем на 7 дней, согласно формуле, список электронных адресов не покажется в поле и уведомление не отправится. Если хватит меньше чем на 7 дней, то формула покажет почты, и функция отправит уведомления.

Также в этом поле проверяется корректность заполнения почт. Если в списке три электронных адреса, где одна почта указана некорректно, то сообщение отправится только двум электронным адресам.

Как применить к своему проекту:

Шаг 1. Переходим в Google-таблицу, создаем копию

Шаг 2. Указываем название клиента в столбце Имя

Шаг 3. Указываем токен аккаунта в столбце «Токен». Приложение для получения токена.

Шаг 4. Указываем логин аккаунта в столбце «Логин»

Шаг 5. Указываем нужное количество дней в столбце «Расход за дней»

Шаг 6. Пишем тему и текст письма в столбцах «Тема сообщения» и «Сообщение»

Шаг 7. Указываем список электронных адресов для отправки

Шаг 8. Скопируйте id вашей таблицы. Перейдите в Расширение -> Apps Script. Вставьте id в переменную в первой строке

Шаг 9. Предоставьте разрешения скрипту подключаться к внешним сервисам и отправлять письма

Шаг 10. Установите триггер отправки по времени

В добавление триггера для проекта устанавливаем следующие параметры:

Выберете функцию: balanceShedule

Выберете, какое развертывание выполнить: Основное развертывание

Источник мероприятия: Триггер по времени

Выберете тип триггера: По дням (для того, что бы получать уведомления раз в день)

Выберете необходимое время

Возможности этого инструмента более широкие. Поскольку в таблице есть формула YandexDirectReport можно отправлять статистику по расписанию. Например, настроить уведомление о расходе каждый час или о снижении открута по сравнению с предыдущим днем.

Надеемся, что это решение позволит всем кто занимается контекстной рекламной освободить время от рутинных операций.

На практике подобный инструмент мы используем в наших проектах и передаём баланс в Telegram, отправляем на почту, также применяем при отчетности в Google Data Studio, Power BI, Tableu.

Выдает ошибку
TypeError: Cannot set property ‘Logins’ of undefined (строка 137).

Не починили? То же самое(

Помогите пожалуйста решить проблему: TypeError: Cannot set properties of undefined (setting ‘Logins’) (строка 137).

Нашел решение:
Переходим в Расширение — Apps Scripts, ищем функцию YandexDirectBalance.
Заменяем весь код этой функции на:

Trigger Email Reminders Based on Dates in Google Sheets

Recently I was asked to set up a system that sends an email reminder about expiring subscriptions listed in a Google Sheet. I completed this task using a Google Sheets script. I am going to show you how to set this up on your own. If you are just copying and pasting the script, don’t forget to change the recipient email to your own, paste in your email where it says subscriptionscript@gmail.com .

Note: if you’re reaching out for help please provide your script and share a sample of your spreadsheet with me.

This article is split into three sections:

Creating your Google script.

Here is a sample Google Sheet I will be using to explain the process. The trigger is based on the date in the expiration date column (column G).

Here is what the email reminder looks like.

To add a script click Tools in the menu bar and then script editor. A new window will open and this is where we’ll write our script.

Below is the script we will be using. I will discuss what each part of the script is doing so you can understand and customize it to your needs.

Let’s break it down.

This part of the code is saving different dates into variables such as: today , twoWeeksFromToday , and oneMonthFromToday . My client requested email alerts of subscriptions that are expiring on the current day, 2 weeks from the current day, and 1 month from the current day.

Every time this code runs today’s date will be generated, the date for 2 weeks from now will be generated, and the date for 1 month from now will be generated.

I am creating variables for the day, month, and year of each of these dates to compare with the day, month, and year of the expiration dates on the sheet. I’m creating these variables because JavaScript dates include time. If we compare 2 dates that are the same but have different times, no email alerts will be sent out.

Other things to consider:

  • When you use the .getMonth() method, January will equate to 0, February to 1, and so on. I add 1 to the month variable so we get the correct number for the month.
  • twoWeeksFromToday.setDate(twoWeeksFromToday.getDate() + 14); I had to play around with adding 14 days to the current date. This ensures that the month changes if 2 weeks from today’s date is inside of a different month.
  • If you want to log out any data, use Logger.log() , run your script, and then click View -> Logs to see what is output. Skip to the Running the Script section to learn how to run your script if you’d like to view logs. Before you run your script make sure you save it, I named mine emailAlert . You can save it using File -> Save.

This part of the code is grabbing the actual data we need from the spreadsheet. Learn more about these methods here.

  • SpreadsheetApp.getActiveSheet() This gets the active sheet in the spreadsheet. I only have one sheet in my example. If you have multiple sheets you may want to use SpreadsheetApp.getSheetByName(name)
  • var startRow tells the script the first row we want to look at
  • var numRows tells the script the number of rows to process
  • sheet.getRange(startRow, 1, numRows, 999) The parameters for this method are: the first row you want to get data from, the first column you want to get data from, the number of rows you’d like to get data from, and the number of columns you’d like to get data from.
  • dataRange.getValues() this is taking the range we declared and grabbing the data we want to look at.

Next, we loop through the data we just grabbed using a standard for loop. We grab 1 row of data to examine. It may be helpful to use Logger.log() here to see what you’re looking at! You could insert Logger.log(row) underneath the row variable to see what the row contains.

The next part of the code is formatting the email that will be sent. This code is a bit ugly but unfortunately, you cannot use template literals inside of Google Scripts yet.

I put the expiration date in the subject of the email as well as the body of the email so I wanted to remove the time from that date to make it look prettier. This is whats going on in the expireDateFormat variable.

I save an empty variable called subject . We will customize this based on the timeframe of the expiration date. The message variable will be the body of our email. It contains information from the rows in the spreadsheet. I insert data from the spreadsheet by extracting it from the current row array. In this example Name is in the 1st column of the spreadsheet, we can retrieve this information from the first element in the row array which is at the zeroth index row[0] . You don’t have to include every column or piece of information in the body of your email, this is up to you to customize.

Next, I grab the expiration date from the current row we’re looking at. I am using the same format as the dates in the first section of the code.

This part of the code is doing the same thing 3 times in a row, with different date requirements. To explain, I will discuss the code that is checking whether the current row’s expiration date is today.

We compare the expiration date month with today’s month, the expiration date day with today’s day, and the expiration date year with today’s year. If they all match we create a subject line for our email that includes text saying a subscription expires today, the name of the person, and the expiration date.

We then use the MailApp.sendEmail() method to send an email to the recipient. The sendEmail() method takes 3 parameters: the recipient email, the subject, and the message or body of the email. The email will be sent from the owner of the spreadsheet.

We have finished writing our script! How do we run it?

Running the Script.

To run your script press the play button located in the menu. Before you run your script you will be required to save it.

After you hit the play button, a pop-up window will appear saying Authorization is required. Click Review Permissions.

Next, you will have to sign in to your Google account. Choose the account you’d like to log into.

After you log in, the pop up will say This app isn’t verified. Click Advanced.

After you click advanced, more text will pop up. Click Go to email alert (unsafe). email alert is what my script is saved as it may say something different if you saved your script under a different name.

Next the popup will say email alert wants to access your Google Account. Click Allow. The pop up should close and we will be able to run our script. Create a row of fake data with today’s date to test your script. Click the play button to run the script. If everything is working correctly, you should have received an email.

Scheduling the Script to Autorun.

Next, I will tell you how to automatically run this script every day or every week or however often you’d like. It would be cumbersome to have to manually run this script every day.

First, let’s make sure we are working in the correct time zone. Click File in the top menu, then click Project Properties. A modal will pop up and you will be looking at the info tab. Scroll down to the bottom and there will be a section called Time zone. Choose the time zone you are in. I am in NYC so I am choosing GMT-05:00 Eastern Time.

Screenshots showing how to choose the correct time zone when setting up a script.

Now let’s set up our trigger. Press edit in the menu and then click Current project’s triggers. A new window will open. Click the blue +Add Trigger button in the bottom right corner.

A modal will pop up that allows us to configure our trigger. There are a few options you can choose from based on how / when you’d like your script to run. My client wanted their script to run every morning so when they got into work they could review any customers with expiring subscriptions. Below is a photo of my preferences.

We only have one function in our file so emailAlert is the only function to choose.

We only have Head as a deployment option.

I want my script to run every day at a certain time so I chose Time-driven as the event source.

I want a daily trigger, so I chose Day Timer. Other options are hourly / monthly / weekly.

Select Time of day allows you to choose when the script will run. My script runs in the morning between 6 am-7 am.

Another way to set up the trigger is based on when the spreadsheet is touched, to set this up your event source will be From spreadsheet. You then have the option to run the script when the spreadsheet is opened, when it is edited, when it is changed, or when a form is submitted. There are lots of different options here so feel free to play around!

Click save and your script will trigger based on the preferences you choose. I suggest inputting a couple of fake rows/dates in your spreadsheet for tomorrow or the next day to make sure the script is working properly.

I hope this was a helpful tutorial. If you have any questions or a way to optimize this solution feel free to leave a comment below. You can also reach me on Twitter or LinkedIn.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *