Saltar para o conteúdo principal
Versão: v20 R4 BETA

Fórmulas e funções

Usando fórmulas

Uma fórmula de planilha é uma expressão que calcula o valor de uma célula.

Introduzir fórmulas

Para introduzir uma fórmula numa área 4D View Pro:

  1. Selecione a célula onde você digitará a fórmula ou função.
  2. Digite = (o sinal de igual).
  3. Digite a fórmula e pressione a tecla Enter.

Ao escrever uma fórmula, pode utilizar diferentes atalhos:

  • clique numa célula para introduzir a sua referência na fórmula:

  • digite a primeira letra de uma função para entrar. Um menu pop-up que lista as funções e referências disponíveis é exibido, permitindo que você selecione os elementos desejados:

Você também pode criar fórmulas nomeadas que podem ser chamadas por seu nome. Para fazer isso, insira essas fórmulas usando o comando [VP ADD FORMULA NAME] (method-list.md#vp-add-formula-name).

Operadores e Operandos

Todas as fórmulas têm operandos e operadores:

Valores e operadores

4D View Pro suporta cinco tipos de dados. Para cada tipo de dados, há suporte para valores literais e operadores específicos.

Tipos de dadosValoresOperadores
Number1.2
1.2 E3
1.2E-3
10.3x
- (adição)
- (subtração)
* (multiplicação)
/ (divisão)
^ (expoente, o número de vezes para multiplicar um número por ele mesmo)
% (porcentagem -- dividir o número antes do operador por cem)
Date10/24/2017* (data + número de dias -> data)
+ (data + hora -> data + hora do dia)
- (data - número de dias -> data)
- (data - data -> número de dias entre as duas)
Time10:12:10Operadores de duração:
+ (adição)
- (subtração)
* (duração * número -> duração)
/ (duração / número -> duração)
String'Sophie' ou "Sophie"& (concatenação)
BooleanTRUE ou FALSE-

Operadores de comparação

Os operadores a seguir podem ser usados com dois operandos do mesmo tipo:

OperadorComparação
=igual a
<>diferente de
>maior que
<menor que
> =maior ou igual a
<=menor que ou igual a

Precedência do operador

Lista dos operadores, do mais importante para o menos importante:

OperadorDescrição
()Parênteses (para agrupamento)
-Negativo
*Mais
%Porcentagem
^Expoente
- e /Multiplicar e dividir
* e -Adicionar e subtrair
&Concatenar
= > < >= <= <>Comparar

Referências de células

As fórmulas referem-se frequentemente a outras células através de endereços de células. Pode copiar estas fórmulas para outras células. Por exemplo, a fórmula a seguir, inserida na célula C8, adiciona os valores nas duas células acima dela e exibe o resultado.

= C6 + C7

Essa fórmula se refere às células C6 e C7. Ou seja, 4D View Pro é instruído a consultar essas outras células para obter os valores a serem usados na fórmula.

When you copy or move these formulas to new locations, each cell address in that formula will either change or stay the same, depending on how it is typed.

  • A reference that changes is called a relative reference, and refers to a cell by how far left/right and up/down it is from the cell with the formula.
  • A reference that always points to a particular cell is called an absolute reference.
  • You can also create a mixed reference which always points to a fixed row or column.

Notação de referências

If you use only cell coordinates, for example, C5, 4D View Pro interprets the reference as relative. You may make the reference an absolute reference by putting a dollar sign in front of the letter and the number, as in $C$5.

You can mix absolute and relative references by inserting a dollar sign in front of the letter or the number alone, for example, $C5 or C$5. A mixed reference allows you to specify either the row or the column as absolute, while allowing the other portion of the address to refer relatively.

A convenient, fast and accurate way to specify an absolute reference is to name the cell and use that name in place of the cell address. Uma referência a uma célula nomeada é sempre absoluta. You can create or modify named cells or named cell ranges using the VP ADD RANGE NAME method.

A tabela seguinte mostra o efeito das diferentes notações:

ExemploTipo de referênciaDescrição
C5RelativoReference is to the relative location of cell C5, depending on the location of the cell in which the reference is first used
$C$5AbsolutoA referência é absoluta. Referir-se-á sempre à célula C5, independentemente do local onde for utilizada.
$C5MixedReference is always to column C, but the row reference is relative to the location of the cell in which the reference is first used.
C$5MixedReference is always to row 5, but the column reference is relative to the location of the cell in which the reference is first used
Nome da célulaAbsolutoA referência é absoluta. Will always refer to the named cell or range no matter where the reference is used.

Funções incorporadas

Spreadsheet functions are preset formulas used to calculate cell values. When you type the first letter of the function to enter, a pop-up menu listing the available functions and references appears, allowing you to select the desired elements:

See SpreadJS's extented list of functions for details and examples.

Funções 4D

4D View Pro allows you to define and call 4D custom functions, which execute 4D formulas. Using 4D custom functions extends the possibilities of your 4D View Pro documents and allows powerful interactions with the 4D database.

4D custom functions provide access, from within your 4D View Pro formulas, to:

  • Variáveis processo 4D,
  • campos,
  • métodos projeto,
  • Comandos de linguagem 4D,
  • ou qualquer expressão 4D válida.

4D custom functions can receive parameters from the 4D View Pro area, and return values.

You declare all your functions using the VP SET CUSTOM FUNCTIONS method. Exemplos:

o:=New object

//Name of the function in 4D View Pro: "DRIVERS_LICENCE"
$o.DRIVERS_LICENCE:=New object

//process variable
$o.DRIVERS_LICENCE.formula:=Formula(DriverLicence)

//table field
$o.DRIVERS_LICENCE.formula:=Formula([Users]DriverLicence)

//project method
$o.DRIVERS_LICENCE.formula:=Formula(DriverLicenceState)

//4D command
$o.DRIVERS_LICENCE:=Formula(Choose(DriverLicence; "Obtained"; "Failed"))

//4D expression and parameter
$o.DRIVERS_LICENCE.formula:=Formula(ds. Users.get($1). DriverLicence)
$o.DRIVERS_LICENCE.parameters:=New collection
$o.DRIVERS_LICENCE.parameters.push(New object("name"; "ID"; "type"; Is longint))

See also 4D View Pro: Use 4D formulas in your spreadsheet (blog post)

Exemplo Hello World

We want to print "Hello World" in a 4D View Pro area cell using a 4D project method:

  1. Crie um método projeto "myMethod" com o seguinte código:
 #DECLARE->$hw Text
$hw:="Hello World"

  1. Execute the following code before opening any form that contains a 4D View Pro area:
  Case of
:(Form event code=On Load)
var $o : Object
$o:=New object
// Define "vpHello" function from the "myMethod" method
$o.vpHello:=New object
$o.vpHello.formula:=Formula(myMethod)
VP SET CUSTOM FUNCTIONS("ViewProArea";$o)
End case
  1. Editar o conteúdo de uma célula numa área 4D View Pro e digitar:

    "myMethod" é então chamado por 4D e a célula aparece:

Parâmetros

Parameters can be passed to 4D functions that call project methods using the following syntax:

=METHODNAME(param1,param2,...,paramN)

These parameters are received in methodName in $1, $2...$N.

Observe que os ( ) são obrigatórios, mesmo que nenhum parâmetro seja passado:

=METHODWITHOUTNAME()

You can declare the name, type, and number of parameters through the parameters collection of the function you declared using the VP SET CUSTOM FUNCTIONS method. Optionally, you can control the number of parameters passed by the user through minParams and maxParams properties.

For more information on supported incoming parameter types, please refer to the VP SET CUSTOM FUNCTIONS method description.

nota

If you do not declare parameters, values can be sequentially passed to methods (they will be received in $1, $2...) and their type will be automatically converted. Dates in jstype will be passed as object in 4D code with two properties:

PropriedadeTipoDescrição
valueDateValor data
timeRealTempo em segundos

4D project methods can also return values in the 4D View Pro cell formula via $0. São suportados os seguintes tipos de dados para os parâmetros devolvidos:

  • text (converted to string in 4D View Pro)

  • real/longint (converted to number in 4D View Pro)

  • date (converted to JS Date type in 4D View Pro - hour, minute, sec = 0)

  • time (converted to JS Date type in 4D View Pro - date in base date, i.e. 12/30/1899)

  • boolean (converted to bool in 4D View Pro)

  • picture (jpg,png,gif,bmp,svg other types converted into png) creates a URI (data:image/png;base64,xxxx) and then used as the background in 4D View Pro in the cell where the formula is executed

  • object with the following two properties (allowing passing a date and time):

    PropriedadeTipoDescrição
    valueDateValor data
    timeRealTempo em segundos

If the 4D method returns nothing, an empty string is automatically returned.

É devolvido um erro na célula 4D View Pro se:

  • o método 4D retorna outro tipo além do listado acima
  • an error occurred during 4D method execution (when user clicks on "abort" button).

Exemplo

var $o : Object

$o.BIRTH_INFORMATION:=New object
$o.BIRTH_INFORMATION.formula:=Formula(BirthInformation)
$o.BIRTH_INFORMATION.parameters:=New collection
$o.BIRTH_INFORMATION.parameters.push(New object("name";"First name";"type";Is text))
$o.BIRTH_INFORMATION.parameters.push(New object("name";"Birthday";"type";Is date))
$o.BIRTH_INFORMATION.parameters.push(New object("name";"Time of birth";"type";Is time))
$o.BIRTH_INFORMATION.summary:="Returns a formatted string from given information" VP SET CUSTOM FUNCTIONS("ViewProArea"; $o)

Compatibidade

Alternate solutions are available to declare fields or methods as functions in your 4D View Pro areas. These solutions are maintained for compatibility reasons and can be used in specific cases. However, using the VP SET CUSTOM FUNCTIONS method is recommended.

Referência a campos utilizando a estrutura virtual

4D View Pro allows you to reference 4D fields using the virtual structure of the database, i.e. declared through the SET TABLE TITLES and/or SET FIELD TITLES commands with the * parameter. This alternate solution could be useful if your application already relies on a virtual structure (otherwise, using VP SET CUSTOM FUNCTIONS is recommended).

WARNING: You cannot use the virtual structure and VP SET CUSTOM FUNCTIONS simultaneously. As soon as VP SET CUSTOM FUNCTIONS is called, the functions based upon SET TABLE TITLES and SET FIELD TITLES commands are ignored in the 4D View Pro area.

Requisitos

  • The field must belong to the virtual structure of the database, i.e. it must be declared through the SET TABLE TITLES and/or SET FIELD TITLES commands with the * parameter (see example),
  • Table and field names must be ECMA compliant (see ECMA Script standard),
  • O tipo de campo deve ser compatível com 4D View Pro (veja acima).

An error is returned in the 4D View Pro cell if the formula calls a field which is not compliant.

Chamar um campo virtual numa fórmula

To insert a reference to a virtual field in a formula, enter the field with the following syntax:

TABLENAME_FIELDNAME()

For example, if you declared the "Name" field of the "People" table in the virtual structure, you can call the following functions:

=PEOPLE_NAME()
=LEN(PEOPLE_NAME())

If a field has the same name as a [4D method], it takes priority over the method.

Exemplo

We want to print the name of a person in a 4D View Pro area cell using a 4D virtual field:

  1. Criar uma tabela "Employee" com um campo "L_Name":

  1. Execute o seguinte código para inicializar uma estrutura virtual:

    ARRAY TEXT($tableTitles;1)
    ARRAY LONGINT($tableNum;1)
    $tableTitles{1}:="Emp"
    $tableNum{1}:=2
    SET TABLE TITLES($tableTitles;$tableNum;*)

    ARRAY TEXT($fieldTitles;1)
    ARRAY LONGINT($fieldNum;1)
    $fieldTitles{1}:="Name"
    $fieldNum{1}:=2 //last name
    SET FIELD TITLES([Employee];$fieldTitles;$fieldNum;*)
  2. Edite o conteúdo de uma célula na área do 4D View Pro e digite "=e":

  1. Selecionar EMP_NAME (utilizar a tecla Tab) e introduzir o fecho.

  1. Validar o campo para apresentar o nome do empregado atual:

A tabela [Employee] tem de ter um registo atual.

Declaração dos métodos permitidos

You can call directly 4D project methods from within your 4D View Pro formulas. For security reasons, you must declare explicitly methods that can be called by the user with the VP SET ALLOWED METHODS method.

Requisitos

Para ser chamado numa fórmula 4D View Pro, um método projeto deve ser:

  • Allowed: it was explicitly declared using the VP SET ALLOWED METHODS method.
  • Runnable: it belongs to the host project or a loaded component with the "Shared by components and host project" option enabled (see Sharing of project methods).
  • Not in conflict with an existing 4D View Pro spreadsheet function: if you call a project method with the same name as a 4D View Pro built-in function, the function is called.

If neither the VP SET CUSTOM FUNCTIONS nor the VP SET ALLOWED METHODS method has been executed during the session, 4D View Pro custom functions rely on allowed methods defined by 4D's generic SET ALLOWED METHODS command. In this case, the project method names must comply with JavaScript Identifier Grammar (see ECMA Script standard). The global filtering option in the Settings dialog box (see Data Access) is ignored in all cases.