Family Encyclopedia >> Work

How to create custom functions in Google sheets

Have you ever wished your spreadsheet was as smart as you are? Well, you may never be that smart, but with a little help from Google Scripts, you can create your own custom functions and get a little closer to that goal.

Google Sheets already has a host of great features for handling number calculations, searching, and string manipulation, among others. However, you may have to build long or complex formulas that are difficult or impossible with the built-in options. If this is you, then you should consider taking the next step and creating your own custom functions. This article will demonstrate how to achieve this using a simple Google Script.

Built-in functions

Spreadsheets already have some very powerful features built in, and Google Sheets is no exception when it comes to cool things you can do right out of the box. Perform Amazing Functions With These Useful Google Spreadsheet Functions power Excel had over me because of the amazing things... Read More A simple example of built-in functions would be “Sum” or “Average:”

How to create custom functions in Google sheets

What if you want to perform a dynamic calculation that the current functions just don't handle? Consider a scenario where you want to add the tax amount to a purchase. Since tax rates vary by location, you'll need to create a function with a long list of logical “ifs”. It would look something like this:

'= if (A2 = "PA", B2 * 0.06, if (A2 = "CA", B2 * 0.0625, B2 * 0))'

Now imagine if you had to add a dozen or more conditions to this statement. It gets unmanageable fast. Sure, there are other ways to handle this, such as adding the information to another table and performing an Excel lookup function of vlookup 4 to efficiently search spreadsheets. 4 Excel search functions to efficiently search your spreadsheets. so far. Be smart and let the formulas do the hard work. Search formulas save time and are easy to apply. Read More Let's get started.

Create a custom function

If you're new to scripting, fear not! It is quite simple to use. The following example will get you started, and if you really want to dig into the topic to gain a deeper understanding of Google Script, we've got you covered on Learning Google Script:5 Best Sites and Tutorials to Bookmark. Google Script Learning:5 Best Sites and Tutorials. to Bookmark Do great new things with the Google services you use every day. Extend and automate by learning Google's cloud-based scripting language. Read more.

1. Open the script editor

From within your sheet select Tools> Script editor

How to create custom functions in Google sheets

2. Create your function

You'll want to give your function a useful name; Verbs work fine. The information that you will paste into your function will go inside the parentheses as variables. Usually this will just be the cell value you want to work with, but if you have more than one value, just separate them with a comma.

To use this tax example, you can copy and paste this code into the script editor:

 función de impuesto (entrada, ubicación) var rate = 0; interruptor (ubicación) caso 'PA': tasa = 0.06; descanso; caso 'CA': tasa = 0.0625; descanso; por defecto: tasa = 0; retorno (entrada * tasa); 

How to create custom functions in Google sheets

Note: You can see that I've only included two locations in this example, just to give you an idea. You can add more by simply adding additional "case" and "rest" lines with additional locations as required. This will be a good practice..

3. Save your function

Select File> Save , Give your project a name and click OK .

How to create custom functions in Google sheets

Use your custom function

Now the fun begins! Once you've created your function, you can start using it the same way you would use a built-in function. In the cell where you want your calculation to display, enter “=yourFunctionName(inputs)”

Para nuestro ejemplo de impuestos estamos usando dos entradas. La ubicación que determinará la tasa de impuesto y el precio del producto que necesita impuesto que se le aplica:

“=impuesto (B2, A2)” donde B2 es el precio del producto y A2 es la ubicación del impuesto.

How to create custom functions in Google sheets

Puede usar las habilidades de Microsoft Word y Excel de Autocompletar 5 que debe tener para tener éxito en la Oficina. 5 habilidades de Microsoft Word y Excel que debe tener para tener éxito en la Oficina "¡Envíeme el informe, lo antes posible!" A basic set of Microsoft Excel and Word tricks can make this task less stressful and help you prepare a stylish report in no time. Lea más para arrastrar y soltar su función en todas sus filas, tal como lo haría con una función incorporada:

How to create custom functions in Google sheets

Después de que haya creado su primera función personalizada, probablemente tendrá muchas más que le gustaría agregar y puede hacerlo sin ningún problema. Simplemente siga los pasos anteriores para crear una nueva función de la misma manera y agréguela a su trabajo existente.

How to create custom functions in Google sheets

El script anterior produce el siguiente resultado:

How to create custom functions in Google sheets

Reutilizar sus funciones

No dejes que todo ese trabajo duro se desperdicie. Usted querrá usar sus funciones personalizadas de nuevo. Incluso si no los necesita todos en hojas futuras, no hay razón para no tenerlos a su disposición..

Puedes reutilizar tu trabajo de dos maneras diferentes:

  1. Guarde sus funciones en una hoja en blanco y utilícela como una plantilla personal utilizando una copia para todas las hojas futuras:

How to create custom functions in Google sheets

  1. Copia y pega tus funciones de una hoja a la siguiente. Esto es tedioso, pero funcionará. Simplemente abra el editor de scripts y copie todo el código de una hoja y luego abra el editor de scripts en otra hoja y pegue el código allí..
  2. Guarda tu hoja en la galería de plantillas de Google. Tenga en cuenta que esto hará que su documento sea accesible para otros. Podrá limitarlo a los miembros de su dominio si tiene una suscripción a Google Apps for Work, de lo contrario, estará disponible públicamente. Si no ha utilizado la galería de plantillas anteriormente, vale la pena echarle un vistazo, ya que hay muchas otras plantillas útiles para hacer su vida más fácil 24 Plantillas de Google Docs que harán su vida más fácil 24 Plantillas de Google Docs que harán su vida más fácil Plantillas Te puede ahorrar mucho tiempo. We've compiled 24 time-saving Google Docs templates for work, health, home, and travel. Get on with your projects, instead of struggling to put documents together. Lee mas !

Documenta tu trabajo

Google Script admite el formato JSDoc, que le permite agregar comentarios a su fórmula para documentar y brindar contexto de ayuda.

How to create custom functions in Google sheets

Esto no es necesario, pero sin duda le dará a su trabajo una sensación profesional y le ahorrará muchas preguntas si planea compartir su trabajo con otros..

How to create custom functions in Google sheets

Puedes hacer tantas cosas geniales con Google Script. Crear funciones personalizadas para Google Sheets es definitivamente una de ellas. Ahora puedes salir de la caja celular y haga que las hojas de Google sean más funcionales que las hojas de Excel:¿Cuál es mejor para usted? Excel vs. Google Sheets:Which is better for you? Do you really need Excel? Both desktop and online solutions have their advantages. If you're having trouble choosing between Excel and Google Sheets to manage your spreadsheets, let us help you decide. Lea más para sus necesidades individuales. Para obtener más información sobre la creación de funciones personalizadas, Google tiene un excelente artículo de conocimiento para que explore.

¿Alguna vez has creado funciones personalizadas en Google Sheets? ¿Tienes alguna que quieras compartir en los comentarios??