Practice Exercise 5
Objective: Practice the for loop and if statement.
Develop a program that produces a straight-line depreciation table for a capital asset, as shown below. The user enters the purchase price and the term in years over which the asset is to be depreciated. The depreciation table should display the year, yearly depreciation (constant except for possibly the last year), end-of-year value, and accumulated depreciation. All values should be rounded to the nearest value (Long or Integer).
Here is a demo.
Your output will probably be relatively unformatted compared to the demo. It is difficult to format a series of numbers that appear on the same line. One approach is to adjust the number of leading spaces so that they justify the value. (vbTab doesn't work well here because a tab indicates the starting position of a field, i.e., it left justifies it. If you want it right justified you have to do additional work.)
If you know the total number of character positions required by the leading spaces and the number itself (which would be 4 in the case of the year), you can determine the number of leading spaces by subtracting the actual number of digits in the value from the total number of characters. In the case of the year, the total number of characters is 4, the single digit year in the example requires one position, so the number of leading blanks is 4 - 1 or 3. For double digit years it would be 4 - 2 or 2 leading blanks.
You can copy the following function into your program to determine the length of a value:
Private Function numDigits(num As
Integer) As Integer
When you add the value to the list box you can use a line like
lstResult.Items.Add Space(4 - numdigits(year)) & year ...
The Space( ) function provides the leading spaces, and the year provides the value for the year variable.
Download an example of this type of listbox.
Straight Line Depreciation
This exercise will assume a salvage value of 0 to simplify matters.