MACRO LIBRARY

Lesson 1.4 homework solution

Free public access. No account or subscription required.

Files

Lesson 1.4 homework solution

Code

'Homework 1.4
'Problem: Imagine you run a business that sells pipe of different lengths and materials. _
    Create a macro that displays a message box for each order.  This message box states the _
    number of segments and the total cost.  Segments are sold in 20 foot lengths only, _
    therefore if a customer ordered 105 feet, 6 segments are needed.  Also, orders under 100 _
    feet cost an additional $20.  If the desired length is less than 20 feet, one segment is _
    still ordered.  The pipe material can be PVC ($40/segment), copper ($50/segment), stainless _
    steel ($60/segment), or titanium ($100/segment).  The only two variables that should be _
    modified by the user are the number of segments and the material. _
'Note #1: I am using feet and dollars arbitrarily.  You can use whatever length units and _
    currency system you want.
'Note #2: There are several ways that this macro could be created.  My solution is just one.
    
Option Explicit
    
Dim intCost As Integer
Dim intTubeLength As Integer
Dim intSegments As Integer
Dim strMaterial As String
Dim blnDiscount As Boolean
    
Sub main()
    'set initial values
    intCost = 0
    intSegments = 0
    blnDiscount = False
    
    'user defined values
    intTubeLength = 0
    strMaterial = "Titanium"
    
    'determine number of segments
    intSegments = intTubeLength \ 20
    If intSegments < 1 And intTubeLength <> 0 Then
        intSegments = 1
    End If
    
    If intTubeLength Mod 20 <> 0 Then intSegments = intSegments + 1
    
    'find cost based on material and number of segments
    Select Case strMaterial
        Case "PVC"
            intCost = intCost + intSegments * 40
        Case "Copper"
            intCost = intCost + intSegments * 50
        Case "Stainless steel"
            intCost = intCost + intSegments * 60
        Case "Titanium"
            intCost = intCost + intSegments * 100
        Case Else
            MsgBox "Material not recognized."
            Exit Sub
    End Select
    
    'discount applies to orders of over 100 feet
    If intTubeLength > 100 Then
        intCost = intCost + 20
        blnDiscount = True
    End If
    
    'display results
    MsgBox "The total cost is: $" & intCost & vbCrLf & "Segments required: " _
        & intSegments & vbCrLf & "Discount applied: " & blnDiscount
End Sub