 Windows Server Application Server SQL Server Windows Windows Phone Sharepoint Programming Programming

# Programming Excel with VBA and .NET : Tasks in Visual Basic - Do Math

7/18/2011 5:29:15 PM
Visual Basic provides built-in operators and functions that perform many of the same calculations that you are used to using from Excel formulas. If you are new to programming, the way you write mathematical formulas in Visual Basic may seem backward:
`    x = 43 + 37 / 2 ' Not 43 + 37 / 2 = x`

That's because the equals sign (=) performs an operation called assignment . The result of the preceding calculation is assigned to the variable x. In Visual Basic, the assignment operation is always performed last, after all other operations. Other operators are evaluated in the sequence shown in Table 1.

##### Table 1. Visual Basic mathematical operators' order of precedence (left to right)
( ) group^ exponent- negation* multiply/ divide
\ integer divideMod modulus+ add− subtract= assign

Most of these operators are self-explanatory, but there are two exceptions:

• Use \ to divide two numbers and ignore the remainder.

• Use Mod to divide two numbers and return only the remainder.

For example, the following simple function divides two numbers and returns the result as a string:

`    Function IntegerMath(numerator As Integer, denominator As Integer) As String        Dim quotient As Integer, remainder As Integer        ' Find the quotient.        quotient = numerator \ denominator        ' Find the remainder        remainder = numerator Mod denominator        ' Return the result        IntegerMath = "Result is " & quotient & " remainder " & denominator    End Function					  `

Mod is frequently used in loops to perform some task once every N number of times. For example, the following code fragment builds a single string out of an array of words and adds a paragraph break every five words:

`    For i = 0 To UBound(words) - 1        str = str & words(i) & " "        If i <> 0 And i Mod 5 = 0 Then _          str = str & vbCrLf    Next`

Visual Basic also provides a set of math functions to perform some common tasks. Since these functions are built in to the language, they are called intrinsic functions . Excel provides equivalent worksheet functions for the intrinsic trigonometric and financial functions listed in Table 2. That duplication reflects the fact that Visual Basic is a general programming language used by many different applications.

##### Table 2. Visual Basic math functions
General
AbsExpFixIntLog
RndSgnSqr
Trigonometric
AtnCosSinTan
Financial
DDBFVIPmtIRRMIRR
NPerNPVPmtPPmtPV
RateSLNSYD

As with the operators, most of the functions in Table 3-5 are self-explanatory with a couple of exceptions:

• Use the Fix or Int function to get the whole-number portion of a decimal number.

• Use Rnd to generate random numbers.

The Rnd function returns a random number between 0 and 1. To generate a random integer between two numbers, use the following formula:

`    ' Returns a random integer that is > min and < max.    Function Random(min As Integer, max As Integer) As Integer        ' Initialize the random-number generator.        Randomize        ' Calculate a random integer.        Random = Int((max - min + 1) * Rnd + min)    End Function`

The Randomize statement initializes the random-number generator. You can repeat sequences of the generated numbers by calling Randomize with a negative number, for example Randomize -1.

You can derive complex functions from Visual Basic's intrinsic functions using the formulas shown in Table 3. These functions are also provided in the sample workbook and there are some worksheet function equivalents as well.

##### Table 3. Derived math functions
FunctionFormula
Secant (Sec)1 / Cos(x)
Cosecant (Cosec)1 / Sin(x)
Cotangent (Cotan)1 / Tan(x)
Inverse Sine (Arcsin)Atn(x / Sqr(-x * x + 1))
Inverse Cosine (Arccos)Atn(-x / Sqr(-x * x + 1)) + 2 * Atn(1)
Inverse Secant (Arcsec)Atn(x / Sqr(x * x - 1)) + Sgn((x) - 1) * (2 * Atn(1))
Inverse Cosecant (Arccosec)Atn(Sgn(x) / Sqr(x * x 1))
Inverse Cotangent (Arccotan)2 * Atn(1) - Atn(x)
Hyperbolic Sine (HSin)(Exp(x) - Exp(-x)) / 2
Hyperbolic Cosine (HCos)(Exp(x) + Exp(-x)) / 2
Hyperbolic Tangent (HTan)(Exp(x) - Exp(-x)) / (Exp(x) + Exp(-x))
Hyperbolic Secant (HSec)2 / (Exp(x) + Exp(-x))
Hyperbolic Cosecant (HCosec)2 / (Exp(x) - Exp(-x))
Hyperbolic Cotangent (HCotan)(Exp(x) + Exp(-x)) / (Exp(x) - Exp(-x))
Inverse Hyperbolic Sine (HArcsin)Log(x + Sqr(x * x + 1))
Inverse Hyperbolic Cosine (HArccos)Log(x + Sqr(x * x - 1))
Inverse Hyperbolic Tangent (HArctan)Log((1 + x) / (1 x)) / 2
Inverse Hyperbolic Secant (HArcsec)Log((Sqr(-x * x + 1) + 1) / x)
Inverse Hyperbolic Cosecant (HArccosec)Log((Sgn(x) * Sqr(x * x + 1) + 1) / x)
Inverse Hyperbolic Cotangent (HArccotan)Log(x + Sqr(x * x - 1))
Logarithm to base N (LogN)Log(x) / Log(n)

Table 2 lists Visual Basic's financial functions. Excel provides its own (larger) set of financial functions.

 Other ----------------- Top 10 - First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)  Video Channel Windows Office Database Application Server