Você está na página 1de 11

14/12/2016 Formula Extension (FOX) Business Planning and Simulation (BWBPS) SAP Library

!a11y>

Formula Extension (FOX)

Use
Você usa a extensão de fórmula DA SEMBPS FOX dentro da função fórmula, a fim de acessar os
dados de transação do pacote de planejamento de forma mais flexível do que quando você
sequencialmente, processa uniformemente todos os registros de dados com a ajuda dos
operadores disponíveis. Além dos operadores de fórmula, a extensão da fórmula oferece a
possibilidade de fazer declarações dependentes das condições, executar loops e emitir
mensagens.
As extensões de fórmula contêm alguns elementos linguísticos fáceis de aprender, com os quais você
pode resolver quase todas as tarefas de planejamento, que ocorrem na prática. A sintaxe deste
elemento linguístico é muito semelhante à linguagem de programação SAP ABAP. Portanto, você
pode usar qualquer conhecimento ABAP existente, sem ter que se preocupar com a complexidade
de uma linguagem de programação completa (por exemplo, gerenciamento de memória, acesso ao
banco de dados).

Integration
As extensões de fórmula não são um tipo de função SEMBPS independente, são um aprimoramento
das fórmulas. Você pode continuar a criar fórmulas da maneira usual, sem ter que fazer uso das
extensões de fórmula.

Features
General
Todas as declarações de extensão da fórmula devem ser concluídas com um período "." Uma declaração
pode se estender por mais de uma linha no editor de fórmulas, e várias declarações podem estar na
mesma linha. Não é feita distinção entre maiús e menos. O sistema converte automaticamente
entradas minúsculas em entradas maiúsdias .
Comments
Você pode criar comentários no editor de fórmulas para explicar as declarações programadas e tornar
o código mais fácil de ler. Para fazer isso, defina o indicador
* na primeira coluna de uma fileira. Isso significa que a linha é ignorada pela verificação de sintaxe, e
é ignorada ao executar a função.

It is important that you write the indicator

http://help.sap.com/saphelp_crm50/helpdata/en/c4/9057425ca611d4b2e30050dadfb23f/content.htm 1/1
14/12/2016 Formula Extension (FOX) Business Planning and Simulation (BWBPS) SAP Library

* in the first column of a row. Otherwise the system will interpret the indicator as a multiplication
operator and report a syntax error.

http://help.sap.com/saphelp_crm50/helpdata/en/c4/9057425ca611d4b2e30050dadfb23f/content.htm 2/1
Syntax
* comment text
Explanations
comment text:
Any character string, which is not interpreted by SEMBPS as a statement. The character string cannot
extend over several lines.
Data Declaration (Local Variables)
Você pode declarar variáveis locais para um grupo de parâmetros no editor de fórmulas. Você usa essas
variáveis, por exemplo, para verificar as condições dinâmicas no tempo de execução da função de
planejamento, que dependem dos valores atuais da figura-chave. Primeiro, você pode determinar o
maior ou menor valor postado de uma figura-chave dentro de um loop usando os dados da transação.
Então você pode salvar esse valor em uma variável e, em seguida, gerar novos dados de plano
independentemente do valor variável. O sistema inicializa variáveis dos tipos
F e eu com o valor 0.

For the language elements


FOREACH and MESSAGE é absolutamente necessário que a referência às características ocorra
através das variáveis declaradas anteriormente. Uma referência direta a uma característica
usando seu nome não é possível com esses elementos de linguagem.
Syntax
DATA varname TYPE typname.
Explanations
varname:
Name of the variable. The name can contain letters and figures, but must always begin with a letter.
The name must differ from the reserved words of the formula extension. All language elements
belong to this (for example
DATA, IF) and all formula operators (for example SIN, CEIL, DECL).
typname:
Name of the data type for the data saved in the variables. The permitted types are divided into two
classes: predefined types and contextspecific types.
Predefined types:
I
: Integer. Used to save whole number values. For example, you use this type for the declaration of control
variables with which you can count the number of iterations in a loop construct.
F: Floating point. Used to save decimals with up to three decimal places; decimal point is the period ".".
You use this type for all calculation operations.
Contextspecific types:
Contextspecific types are types, which refer to the key figures and characteristic in the planning
level to which the formula function belongs. Which types are allowed depends on which
characteristics of the planning level were included in the list of fields to be changed of the formula
function. The correct type name is then identical with the technical name of a characteristic. A
variable whose type refers to a characteristic of the planning level, can accept all values which are
maintained for this characteristic.
The
KEYFIGURE_NAME type is an exception: This type is only allowed, when you have included the generic
entry "key figure name" in the list of fields to be changed. You can program a loop with a variable of this
type, which iterates over all key figures of the planning level. In such a loop, you can for example assign all
key figures the same value, or you can define conditions on which the value assignment should depend.
Example
In the following example, the system loops through all key figures of the planning level using the
KeyFigure variable. Key figures, which contain the value 0, are assigned the value 1. The other key figures
remain unchanged.
DATA KeyFigure TYPE KEYFIGURE_NAME.
FOREACH KeyFigure.
..IF { KeyFigure } = 0.
....{ KeyFigure } = 1.
..ENDIF.
ENDFOR.
Conditional Statement
Here you determine that a statement block is only executed if the specified condition is fulfilled. The
conditional statement is always introduced by the language element
IF and closed with ENDIF. You can include as many alternative conditions in a conditional statement as
you like with the language element ELSEIF. As soon as one of the specified conditions is correct, the
statement block belonging to it is executed, and then the statement is exited. With the language element
ELSE, you can plan one statement block, which is then executed if none of the conditions specified before
apply.
Syntax
IF
expression1.
..statement1.
[ELSEIF
expression2.
..statement2. ]
[ELSE.
..statement3. ]
ENDIF.
Explanations
expression n :
Logical expression. If expression n results in the value
True, then the appropriate statement block statement n is executed. Otherwise the next logical expression
is checked (if available), or the statement block assigned to the language element ELSE is executed (if
available): Then processing is continued behind the language element ENDIF.
You can use the usual comparison operators in a logical expression (=, <>, <, >, <=, >= or EQ, NE, LT,
GT, LE, GE) as well as the following additional operator:
NOT: Inverts the logical value of the subsequent expression.
IS NIL: Delivers the value True, if it was attempted to read over and above the last data record.
IS INITIAL: Delivers the value True, if a key figure or characteristic contains the initial value.
The operators AND and OR are available for the interlinkage of several logical expressions to a complex
expression. You make the grouping of subexpressions within a complex expression with round brackets.
statement n :
Statement block, which is then executed, when the check of the previous logical statement results
in the value
True. Otherwise the statement block is skipped.
Example
In the following example sales per customer are planned. The size of the planned sales increase depends
on the size of previously made sales: The sales with customers, to which a sales revenue of more than
50000 € is already allotted, should increase by 10%, while the increase with customers under this threshold
should amount to 20%. The formula operand used in the example has the form { key figure name,
customer, version }. Version 0 contains the actual data, version 1 the plan data.
DATA Customer TYPE 0CUSTOMER.
FOREACH Customer.
..IF { REVENUE, Customer, 0 } >= 50000.
.... { REVENUE, Customer, 1 } = { REVENUE, Customer, 0 } * 1.1.
..IF { REVENUE, Customer, 0 } >= 50000.
.... { REVENUE, Customer, 1 } = { REVENUE, Customer, 0 } * 1.2.
..ENDIF.
ENDFOR.
Loop Constructs
The formula extensions offer two different language elements for the programming of loops:
DO ... ENDDO and FOREACH ... ENDFOR. Both language elements are used for different
purposes: The statement
DO ... ENDDO executes a statement block between the language elements until a termination condition
is fulfilled. When this condition is fulfilled, processing must be explicitly terminated with the command
EXIT. Processing is continued in this case with the statement which follows ENDDO.
The statement
FOREACH ... ENDFOR executes an iteration over the values of a characteristic sorted in ascending order
(restricted by selection conditions from planning level or package, if required) or over the key figures
contained in the planning level. The reference to the characteristic or list of key figures must always take
place via a previously declared local variable. The termination criterion is implicitly specified when the last
characteristic value or last key figure is reached.
Syntax
1.
DO ... ENDDO
DO.

..statement1.
..IF expression1.
.. .[statement2.]
.... EXIT.
..ENDIF.
ENDDO.
2.
FOREACH ... ENDFOR
FOREACH
varname [, varname].
..statement1.
ENDFOR.
Explanations
expression1:
Logical expression, which defines the termination criterion for loop processing. When expression1
results in the value
True, then the appropriate statement block statement2 is executed (if available). In any case, the EXIT
command must be used when the termination condition is reached, as otherwise there is no possibility to
exit the loop.
statement1:
Statement block, which is executed in every loop pass.
statement2:
Optional statement block, which is executed when the termination condition is reached.
varname:
Variable, which refers to a characteristic contained in the planning level, or to the quantity of key
figures contained in the planning level (type
KEYFIGURE_NAME).

With the
FOREACH loop you can not only iterate over the values of an individual characteristic, but also over
characteristic combinations, which are contained in the transaction data of the package. For this you
should include the characteristics involved in a list separated by commas in the FOREACH statement (for
example FOREACH var1, var2, var3.). In this way, in most cases, you achieve a considerably quicker
processing than with several FOREACH statements nested in each other, which only iterate over one of
the characteristics.
Example
1.
DO ... ENDDO
The example shows how you can calculate the factorial of a number (here the factorial of 5) with the
statement
DO ... ENDDO. ENDDO the factorial of a number (here the factorial of 5) can be calculated. It is very
important that the loop passes are counted in the variable Counter, and the loop is exited with the EXIT
statement when the termination criterion is reached.
DATA Factorial TYPE I.
DATA Counter TYPE I.
DATA Result TYPE I.

Result = 1.
Counter = 0.
Factorial = 5.

DO.
..Counter = Counter + 1.
..IF Counter <= Factorial.
....Result = Result * Counter.
..ELSE.
....EXIT.
..ENDIF.
ENDDO.
2.
FOREACH ... ENDFOR
In the following example, the system loops through all key figures of the planning level. Key figures, which
contain the value 0, are assigned the value 1. The other key figures remain unchanged.
DATA KeyFigure TYPE KEYFIGURE_NAME.
FOREACH KeyFigure.
..IF { KeyFigure } = 0.
....{ KeyFigure } = 1.
..ENDIF.
ENDFOR.
Messages
You can issue messages to point out errors and special features to users when executing a formula
function, or to give information about processing progress with timeconsuming operations.
Syntax
MESSAGE
Tnnn (class) [WITH var1 [[[var2] var3] var4]].
Explanations
T:
Type of message. Allowed values are
E (error) and I (information).

If you issue a message of type


E, then the results of the planning function are not written in the internal transaction data buffer, and can
therefore not be posted (see Saving Concept).
nnn:
Threefigure number of the message to be issued within the message class.
class:
Entry of the message class enclosed in round brackets, to which the message to be issued belongs.

As far as possible, use messages from a message class you created in the ABAP
Workbench. In this way, you make sure that your messages are independent of possible
changes to delivered message classes. However, you must transport the message class you
created, from the test system into the production system.

WITH

var1 [[[var2] var3] var4]:


Optional extra, to issue up to four text variables in the message text. You can use local variables,
which reference characteristics or the list of key figures, as text variables, or text constants. The
text variables are inserted into the static message text (short and long text) in the places, which
were prepared for it with the placeholder
&.
Example
In this example, the planned price of an article is increased by 10% for all customers. If the price for a
customer is with the value 0 in the data basis, then an error message is issued, which also contains the
name of the customer. Because of the system behavior described above with messages of the type E, no
key figure values at all are changed in this case (also not for data records in which the price has a value
different to 0). To execute the price increase, you must first change the data records with the value 0 or
remove it from the selection.
The formula operand used in the example has the form { key figure name, customer, version }. Version 0
contains the actual data, version 1 the plan data.
DATA Customer TYPE 0CUSTOMER.
FOREACH Customer.
..IF { Price, Customer, 0 } = 0.
....MESSAGE E001(/MSG01) WITH Customer.
..ELSE.
... { Price, Customer, 1 } = { Price, Customer, 0 } * 1.1.
..ENDIF.
ENDFOR.
Special Data Access Functions
Access to Time Characteristics
You can access time characteristics with the function
TMVL. The function returns the current value of the specified time characteristic, if necessary, marked up
with an offset, which is also specified. The entry of an offset offers the advantage that in this way such
characteristics can also be delivered, which are not contained in the transaction data of the current planning
package.
Syntax
TMVL(
characteristic name, offset)
Explanations
characteristic name:
Technical name of the time characteristic, whose value should be calculated.
offset:

Whole number offset, with which the current value of the time characteristic is marked up. The entry
of the offset is obligatory. If you want to transfer the value of the time characteristic unchanged, then
enter an offset of 0.
Example
In the following example, the net book values of an asset are calculated with straightline depreciation over
a five year duration of depreciation. Cost price is 1000, net book value 100, depreciation percentage rate
20%. The function
TMVL determines the value of the time characteristic FYEAR and adds an offset of 1. The value increased
by 1, is assigned to FYEAR within the DO...ENDDO loop, so that the calculation of the net book value is
executed for a sequence of five fiscal years. After that the iteration is terminated. The operand for this
formula has the form { key figure name, fiscal year }.
DATA YEAR TYPE I.
DATA FYEAR TYPE 0FISCYEAR.
FYEAR = VARV('ACTYEAR').
DO:
YEAR = YEAR + 1.
. FYEAR = TMVL(FYEAR, 1).
. {0AMOUNT, FYEAR} = DECL(1000, 100, 20, YEAR}.
. IF YEAR = 5.
. . EXIT.
. ENDIF.
ENDDO.
Access to Attributes
With this function, you can access data, which neither concerns characteristics or key figures, but master
data attributes, which can be assigned to a characteristic.

Syntax ATRV(
Th ribute value of a characteristic that is compounded to a superordinate
e characteristic, can only be determined with the ATRV function, if the superordinate
att characteristic is not included in the list of characteristics to be changed.
attributname, varname)
Explanations
attributname:
Technical name of the attribute, whose value should be calculated.
varname:
Variable, which refers to the characteristic, to which the attribute belongs.
Example
In this example, the prices are conducted as attributes for the characteristic article. You use the
ATRV function to determine the attribute value. The function expects the technical name of the attribute to
be read (for example 0PRICE) as parameter, and a variable, which refers to the characteristic, to which the
attribute belongs (for example 0ARTICLE). The operand for this formula has the form { key figure name,
article }.
DATA ARTICLE TYPE 0ARTICLE.
FOREACH ARTICLE.
. {REVENUE, ARTICLE} = ATRV('0PRICE', ARTICLE) * {QUANTITY, ARTICLE}.
ENDFOR.
Access to Variables
With this function, you can determine the value of a (global)
Variable, which was defined in the context of the current planning area.

In the context of formula extensions, only such variables can be used, which are
restricted to single value. Otherwise the system cannot clearly determine the value of
the variables.
Direct access to a global variable using its name (in a value assignment with the form
"{Operator} = varname.") is not possible. Always use the
VARV function for this purpose.
Syntax
VARV(
varname)
Explanations
varname:
Technical name of the variable.
Example
In the following example two variables of the type 0CUSTOMER are declared. One of them is used as a
control variable for an iteration over all customers. The other one is reserved using the
VARV function with the value of the global variable VCUST, as it was defined in the context of the planning
area. In the iteration, as soon as the customer defined by the variable is reached, the planned revenue for
all articles is increased by 10%. Subsequently, the iteration is terminated with the EXIT statement. The
operand for this formula has the form { key figure name, article }.
DATA ARTICLE TYPE 0ARTICLE.
DATA CUSTOMER TYPE 0CUSTOMER.
DATA VCUSTOMER TYPE 0CUSTOMER.

VCUSTOMER = VARV('VCUST').
FOREACH CUSTOMER.
. IF CUSTOMER = VCUSTOMER.
. . FOREACH ARTICLE.
. . . {REVENUE, ARTICLE} = (REVENUE, ARTICLE) * 1.1.
.. ENDFOR.
. . EXIT.
. ENDIF
ENDFOR.
Determination of the Current Characteristic Value
With this function, you can transfer the current value of a characteristic to a variable, and in this way find
out which data was currently edited. The function
OBJV is called up without entering parameters. First the type of the variable (and with it the characteristic,
to which the variable refers) is determined, to which the function result should be assigned. Then the
function determines the current value of the characteristic referenced by the variable, and returns the value
as function result.
Above all, the function is used to keep the list of fields to be changed as small as possible. This has the
following advantages:
The complexity of the formula operands decreases.
Iterations, which are superfluous in content, but syntactically necessary can be reduced using
characteristic values. The performance improves through this.

The result of the function


OBJV can only be assigned to such variables, which were declared with reference to one of the
characteristics, which are not contained in the list of fields to changed of the formula function.
Syntax
varname
= OBJV()
Explanations
varname:
Technical name of the variable.

Example
In the following example, the example used above for the
VARV function is enhanced in the following way: An additional variable is declared of the type
0COUNTRY, to which the current value of the characteristic is transferred within the FOREACH loop.
Revenue planning is executed as in the example above, however, not for articles that were sold in
Germany. Prerequisite for calling up the OBJV() function is that the characteristic 0COUNTRY is not
contained in the quantity of fields to be changed.
DATA ARTICLE TYPE 0ARTICLE.
DATA COUNTRY TYPE 0COUNTRY.
DATA CUSTOMER TYPE 0CUSTOMER.
DATA VCUSTOMER TYPE 0CUSTOMER.
14/12/2016 Formula Extension (FOX) Business Planning and Simulation (BWBPS) SAP Library

VCUSTOMER = VARV('VCUST').
FOREACH CUSTOMER.
. IF CUSTOMER = VCUSTOMER.
. . FOREACH ARTICLE.
. . . COUNTRY = OBJV().
. . . IF COUNTRY = 'DE'.
. . . . {REVENUE, ARTICLE} = (REVENUE, ARTICLE) * 1.1.
. . . ENDIF.
.. ENDFOR.
. . EXIT.
. ENDIF
ENDFOR.

See also:

Formula Extension: Examples

© COPYRI GHT BY SAP SE OR AN SAP AFFI LI ATE COMPANY. ALL RI GHTS RESERVED. –

PRI NTED FROM SAP HELP PORTAL. (ht t p: / / help. sap. com)

http://help.sap.com/saphelp_crm50/helpdata/en/c4/9057425ca611d4b2e30050dadfb23f/content.htm 10/10

Você também pode gostar