VBA2

advertisement
Second VBA program in Excel (use of text boxes and command button)
1. Start Excel and create a blank workbook. Save the file under “Bending Stress” using
Macro-Enabled workbook file format. Click on the Developer and the Visual Basic.
2. Add UserForm1 to “ThisWorkBook”. Change the “caption” of userform1 to “Bending
Stress Form”
3. From the Toolbox grab the “TextBox” and drop it in the UserForm1 window. Drop a
total of 8 Textboxes.
4. Change the text for three of the textboxes to: “Bending Moment”, “Distance to Neutral
Axis”, and “Moment of Inertia”. Set the “locked” property of these boxes to “True” so
they cannot be changed.
5. Place three of the other boxes to the right of these text boxes for the user input of values.
6. Change the text of the 7th textbox to “Bending Stress”.
7. Grab and drop a “Commandbox” in the userform. Change the title of commandbox to
“Calculate”. When the user clicks on the “Calculate” button, the program reads the input
from the textboxes, calculates the bending stress and writes it in the 8th textbox.
8. Select the command button and right click and select “Code”. Whatever code we write
under the command button code will be executed every time the command button is
selected. You can see that the textboxes also have some blank routines that we don’t
need to place any code in them.
9. Just like any other programming language we need to define the necessary variables and
their types. For this program we can define the variables first. Comment lines start with
a quotation mark.
' Variable definitions, Mz is the bending moment, Cy is the distance to Neutral Axis
' Iz is the moment of inertia, Sigma is the resulting stress
Dim Mz As Single
Dim Cy As Single
Dim Iz As Single
Dim Sigma As Single
10. The first three variables are inputs and we can read them from the user input textboxes
(your textbox numbers may be different).
Mz = TextBox4.Value
Cy = TextBox5.Value
Iz = TextBox6.Value
11. Finally we calculate the stress and write it in the results textbox.
Sigma = Mz * Cy / Iz
TextBox8.Value = Sigma
The following line formats Sigma with two digits figures of accuracy
TextBox8.Value = FormatNumber(Sigma, 2)
12. Call the userform from a module and test the program
Download