Coding SubroutinesYoull find uses for subroutines as you begin writing larger applications. For example, suppose you were writing a company sales status program. You might need a specialized routine that calculates a cost of sales value and displays that value in a label. By putting that code in a subroutine procedure, you help separate the task from other tasks and make the application more manageable. In addition, if several procedures in the application need the calculation, you can call the procedure from every place that needs it instead of repeating the same code in every place. To create a subroutine procedure, perform these steps:
After Visual Basic creates the place for the procedure, you can add the body of the code. For example, Listing 13.1 shows how you might code a cost of sales subroutine procedure. The procedures job is to calculate the cost of sales from text box values and assign the cost to a label named lblCost.
Listing 13.1. A cost of sales subroutine. 1: Private Sub CostOfSales() 2: Computes a cost of sales and 3: displays that code in a label 4: Dim curGrossSales As Currency 5: Dim curCostSales As Currency 6: Dim sngOverHead As Single 7: Dim sngInventoryFctr As Single 8: Dim sngPilferFctr As Single 9: 10: Store initial variable values from controls 11: curGrossSales = txtGross.Text 12: sngInventoryFctr = txtTotalInv.Text * 0.38 13: sngPilferFctr = txtPilfer.Text 14: sngOverHead = 0.21 Fixed overhead percentage 15: 16: curCostSales = curGrossSales - (sngInventoryFctr * curGrossSales) 17: curCostSales = curCostSales - (sngPilferFctr * curGrossSales) 18: curCostSales = curCostSales - (sngOverHead * curGrossSales) 19: lblCost.Caption = Format(curCostSales, Currency) 20: End Sub
To call this procedure, another procedure (such as a Click() event procedure or another standard procedure) can issue either of these statements: Call CostOfSales() Calls the CostOfSales() subroutine CostOfSales Calls the CostOfSales() subroutine If the subroutine uses no arguments, you dont need to use Call and the parentheses to trigger the subroutines execution. If CostOfSales() did use one or more arguments, you would not need Call or the parentheses around the list of arguments. |
|
![]() |
![]() |
|||