CMT400 Excercise 3 (Excel VBA) : The Quadratic Solver: A Ac B B A Ac B B
CMT400 Excercise 3 (Excel VBA) : The Quadratic Solver: A Ac B B A Ac B B
You will solve a quadratic equation using worksheet and also userform.
Excercise 3a: The Quadratic Solver( Using Worksheet)
In this exercise, the worksheet will be used as the host application. A button
control will be added in the worksheet and Visual basic codes will be written for
that control. The codes will appear as module in the Visual basic editor.
Please refer to lecture notes for details of the formula used.
Brief summary of the equations are given here.
Case 1: det >0
Root1 = ( b b 2 4ac ) / 2a
Root2 = (b b 2 4ac ) / 2a
Case 2: det =0
Root2 = Root1 = b / 2a
Case 3: det <0
No root
Examples of chemistry problems that requires solving quadratic equation are
a. Chemical equilibrium
b. Acid-base equilibrium i.e calculation of pH of a weak acid or weak base
Procedure
1. Open MS Excel
2. Save the file as QuadraticSolver.xls
3. Type in cells A2, A3 and A4 : a, b and c respectively. Type root 1 and root
2 in the following two cells below i.e A5 and A6 as shown in Fig. 1 below:
4. You do not have to copy the examples of the quadratic functions. These
are just for your reference. You can check your answers later with these
answers.
5. Insert Button(Form Control) by selecting Developer tab > Insert. Choose
from the Form controls not from ActiveX control.
6. Place the button in a suitable place..a macro dialog box appears as in Fig.
2.
7. Change the macro name to QuadSolver and click new. The Visual Basic
editor will automatically open as a module. By default it wll give the name
of the button in increasing order..the name can also be changed if
necessary.
Fig. 1
Fig. 2.
8. Copy the codes below into the module.
Sub Button1_Click()
Dim a, b, c, det, root1, root2 As Single
a = Cells(2, 2)
b = Cells(3, 2)
c = Cells(4, 2)
det = (b ^ 2) - (4 * a * c)
If det > 0 Then
root1 = (-b + Sqr(det)) / (2 * a)