Public Function basConvertUnits(MyVal As Double, FrmUnit As String, ToUnit As String) As Double
Sample Usage:
'frm$ = "Yd"
'ToUnt$ = "Mile"
'Print basConvertUnits(1#, "Mile", "Kilometer")
' 1.60902026512266
'Print basConvertUnits(1#, "Inches", "Kilometer")
'0
'Print basConvertUnits(1#, "In", "Kilometer")
' 2.53847331766782E-05
'Print basConvertUnits(17#, frm$, ToUnt$)
' 9.65909090909091E-03
'I 'm taking a course in Visual Basic and I'm having lots of
'trouble, especially using arrays. For example, our assignment reads:
'Write a program that displays the nine different units of measure,
'request the unit to convert from, the unit to convert to,
'and the quantity to be converted, and then displays the converted quantity.
'1 inch = .0833 foot
'1 rod = 16.5 feet
'1 yard = 3 feet
'1 furlong = 660 feet
'1 meter = 3.2815 feet
'1 kilometer = 3281.5 feet
'1 fathom = 6 feet
'1 mile = 5280 feet
'This is done ONLY to illustate the use of the ARRAYS.
'In any REAL world Process, this would be woefully inadequate.
'You would need to chaek that the from/to Units were both Included and Compatible.
'A "Real" system would include maany different Types of units (Area, Volume, Energy,
'Time, Weight, Mass, Velocity ...). With the myraid of conversions to consider,
'simple arrays used in this example quickly become to complex to be reasonable and
'would generally be replaced by a database/table. Even in this example, You need to
'make sure that the Units are entered correctly, and that SOME value is provided
'for the conversion. Here, we only check that
'both a From and To conversion Units were 'found'. The ONLY indication of a problem
'is the return value (If it is Zero, you can assume ther is a problem!)
'The 'Program" checks that a numeric value is supplied for the Value argument
'and will generate an error if no value is input.
Dim Conv(10) As Single
Dim FromTo(10) As String
Dim Idx As Integer
Dim FrmIdx As Integer
Dim ToIdx As Integer
Conv(1) = 0.0833 'Ft/In
Conv(2) = 3# 'Ft/Yd
Conv(3) = 6# 'Ft/Fathom
Conv(4) = 16.5 'Ft/Rod
Conv(5) = 660# 'Ft/Furlong
Conv(6) = 3281.5 'Ft/Killometer
Conv(7) = 5280# 'Ft/Mile
FromTo(1) = "In"
FromTo(2) = "Yd"
FromTo(3) = "Fathom"
FromTo(4) = "Rod"
FromTo(5) = "Furlong"
FromTo(6) = "Kilometer"
FromTo(7) = "Mile"
'Generic Algorythim for this (simplistic) Example:
'[MyVal] * Conv(From) / Conv(To)
'But, of Course, You need to Relate From & To to valid indicies of Conv
For Idx = 0 To UBound(Conv) 'Loop through (valid) Conversions
If (Conv(Idx) = 0) Then 'Check a Conversion Value Exists
GoTo NoConv 'Don't look For Conv Index if No Value
End If
If (FrmUnit = FromTo(Idx)) Then 'Look Up the From Index
FrmIdx = Idx
End If
If (ToUnit = FromTo(Idx)) Then 'Then the To Index
ToIdx = Idx
End If
NoConv:
Next Idx
If (FrmIdx * ToIdx <> 0) Then
basConvertUnits = MyVal * Conv(FrmIdx) / Conv(ToIdx)
Else
basConvertUnits = 0
End If
End Function