Automating Payment Calculation in Google Docs Using Apps Script
Introduction
Google Apps Script is a powerful tool that allows you to automate tasks within Google Workspace applications, such as Google Docs. In this tutorial, we will create a script that prompts the user to enter their hourly rate and the number of hours worked, then calculates and displays the total payment in an alert box.
Setting Up the Script
To integrate the script with Google Docs, follow these steps:
- Open a Google Doc.
- Click on
Extensions
→Apps Script
. - Delete any existing code and paste the following script:
function onOpen() {
// Add a custom menu to the Google Docs interface
const ui = DocumentApp.getUi();
ui.createMenu('Custom Scripts')
.addItem('Calcular Pago', 'calcularPago')
.addToUi();
}
function calcularPago() {
const ui = DocumentApp.getUi();
// Prompt the user to input the hourly rate
const rateResponse = ui.prompt("Calcular Pago", "Ingrese la tarifa por hora:", ui.ButtonSet.OK_CANCEL);
if (rateResponse.getSelectedButton() !== ui.Button.OK) return; // Exit if the user cancels
const hourlyRate = parseFloat(rateResponse.getResponseText());
if (isNaN(hourlyRate) || hourlyRate <= 0) {
ui.alert("Error", "La tarifa por hora ingresada no es válida. Intente nuevamente.", ui.ButtonSet.OK);
return;
}
// Prompt the user to input the number of hours worked
const hoursResponse = ui.prompt("Calcular Pago", "Ingrese el número de horas trabajadas:", ui.ButtonSet.OK_CANCEL);
if (hoursResponse.getSelectedButton() !== ui.Button.OK) return; // Exit if the user cancels
const hoursWorked = parseFloat(hoursResponse.getResponseText());
if (isNaN(hoursWorked) || hoursWorked <= 0) {
ui.alert("Error", "El número de horas trabajadas ingresado no es válido. Intente nuevamente.", ui.ButtonSet.OK);
return;
}
// Calculate the total payment
const totalPayment = (hourlyRate * hoursWorked).toFixed(2);
// Show the total payment in an alert
ui.alert("Resultado", `El pago total es: $${totalPayment}`, ui.ButtonSet.OK);
}
How It Works
- When the document is opened, a custom menu called Custom Scripts appears in the toolbar.
- Selecting Calcular Pago prompts the user to enter:
- Their hourly rate.
- The number of hours worked.
- The script validates the inputs and calculates the total payment.
- The result is displayed in an alert box.
Example Output
If you input:
- Hourly rate:
$50.00
- Hours worked:
8
The alert will display:
Resultado
El pago total es: $400.00
Conclusion
This simple yet effective Google Apps Script allows users to quickly calculate their earnings without leaving Google Docs. With minor modifications, this script can be extended to include tax calculations, overtime pay, or exporting results to a spreadsheet.
Give it a try and streamline your payment calculations in Google Docs today!