Input validation and repetition in vba - vba

I have the following code and I would like help in 4 areas:
Did I validate the inputbox correctly? It should only take positive numerical variables.
How can I let the input box accept both input with, and without, symbols such as ($)?
How can I link the code so that it can directly request another number if the user has entered a negative non numeric number?
How can I repeat the procedure in the loop directly without repeating the whole code?
Option Explicit
Sub IncomeSalaryCalculation()
Dim strSalary As String
Dim dblTaxableSalary As Double
Dim dblTax As Double
Dim dblSalaryAfterTax As Double
Dim strOutput As String
Dim SalaryCalculationRequest As VbMsgBoxResult
strSalary = InputBox("Please indicate your salary", "Salary Calculation")
If Not IsNumeric(strSalary) Then
MsgBox "This is no number! Please enter a non-negatif number", vbOKOnly, "Error"
ElseIf strSalary < 0 Then
MsgBox "You should enter a positive number", vbOKOnly, "Error"
Else
dblTaxableSalary = CDbl(strSalary)
Select Case dblTaxableSalary
Case Is >= 151000
dblTax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (150000 - 37400) * 0.5 + (dblTaxableSalary - 150000) * 0.5
Case Is >= 37401
dblTax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (dblTaxableSalary - 37400) * 0.4
Case Is >= 2441
dblTax = 2440 * 0.1 + (dblTaxableSalary - 2440) * 0.2
Case Else
dblTax = 2440 * 0.1
End Select
dblSalaryAfterTax = dblTaxableSalary - dblTax
strOutput = "The amount of income tax is " & dblTax & vbNewLine & "Your salary after tax is " & dblSalaryAfterTax
MsgBox strOutput, vbOKOnly, "Final Salary"
Do
SalaryCalculationRequest = MsgBox("Do you want to calculate the tax of a new income?", vbYesNo, "New income tax salary calculation")
If SalaryCalculationRequest = vbYes Then
strSalary = InputBox("Please indicate your salary", "Salary Calculation")
dblTaxableSalary = CDbl(strSalary)
Select Case dblTaxableSalary
Case Is >= 151000
dblTax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (150000 - 37400) * 0.5 + (dblTaxableSalary - 150000) * 0.5
Case Is >= 37401
dblTax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (dblTaxableSalary - 37400) * 0.4
Case Is >= 2441
dblTax = 2440 * 0.1 + (dblTaxableSalary - 2440) * 0.2
Case Else
dblTax = 2440 * 0.1
End Select
dblSalaryAfterTax = dblTaxableSalary - dblTax
strOutput = "The amount of income tax is " & dblTax & vbNewLine & "Your salary after tax is " & dblSalaryAfterTax
MsgBox strOutput, vbOKOnly, "Final Salary"
Else
MsgBox "Glad to serve you"
End If
Loop Until SalaryCalculationRequest = vbNo
End If
End Sub

This should answer your questions without delving into all your code. Tested.
Sub getInput()
Dim ans As String
Do
ans = InputBox("Please indicate your salary", "Salary Calculation")
Loop Until isValid(ans)
''{{{{{{{{
''Do what you need here with the user input (stored in *ans* variable)
''}}}}}}}}
End Sub
Function isValid(ans As String) As Boolean
Dim cleanAns As variant
cleanAns = IIf(ans Like "*$*", Replace(ans, "$", ""), ans)
isValid = IsNumeric(cleanAns) And cleanAns > 0
If Not isValid Then MsgBox "only positive numbers allowed"
End Function

Related

Converting cents into amount of change given

So i am having troubles with this code. I get the dollars part to work correctly but the rest is not. Im trying to change 529 cents into 5 dollars 1 quarter 0 dimes 0 nickels 4 pennies, here is my code.
Option Explicit On
Option Strict On
Module Module1
Sub Main()
Dim amount As Integer
Dim dollars As Integer
Dim quarters As Integer
Dim dimes As Integer
Dim nickels As Integer
Dim pennies As Integer
Console.WriteLine("Please Enter A Unit of Cents")
amount = CInt(Console.ReadLine())
If (amount >= 100) Then
dollars = amount \ 100
amount = amount - (100 * dollars)
ElseIf (amount >= 25) Then
quarters = amount \ quarters
amount = amount - (25 * quarters)
ElseIf (amount >= 10) Then
dimes = amount \ dimes
amount = amount - (10 * dimes)
ElseIf (amount >= 5) Then
nickels = amount \ nickels
amount = amount - (5 * nickels)
ElseIf (amount >= 1) Then
pennies = amount
End If
Console.WriteLine("" & dollars & " dollars " & quarters & " quarters " & dimes & " dimes " & nickels & " nickels " & pennies & " pennies ")
Console.ReadLine()
End Sub
End Module
Write a function to automate the counting of coins. You were almost there. Just use modulo to find the remaining pennies each time a count is done.
Sub Main()
Dim amount As Integer
Dim dollars As Integer
Dim quarters As Integer
Dim dimes As Integer
Dim nickels As Integer
Dim pennies As Integer
Console.WriteLine("Please Enter A Unit of Cents")
amount = CInt(Console.ReadLine())
dollars = parseDenomination(amount, 100)
quarters = parseDenomination(amount, 25)
dimes = parseDenomination(amount, 10)
nickels = parseDenomination(amount, 5)
pennies = amount
Console.WriteLine("" & dollars & " dollars " & quarters & " quarters " & dimes & " dimes " & nickels & " nickels " & pennies & " pennies ")
Console.WriteLine($"{getAmountString(dollars, "Dollar")}, {getAmountString(quarters, "Quarter")}, {getAmountString(dimes, "Dime")}, {getAmountString(nickels, "Nickel")}, {getAmountString(pennies, "Penny")},")
Console.ReadLine()
End Sub
Private Function parseDenomination(ByRef amount As Integer, count As Integer) As Integer
Dim result = amount \ count
amount = amount Mod count
Return result
End Function
Private Function getAmountString(amount As Integer, name As String) As String
Return $"{name}{If(amount = 1, "", "s")}: {amount}"
End Function
I added an additional method to help get the string output. It kind of breaks down for "pennies / pennys" though - that's English for you.

Why is the result of my program always underweight in BMI?

Here is my code:
Dim Weight, Height, Bmi_value As Integer
Weight = TextBox1.Text
Height = TextBox2.Text
Bmi_value = (Weight / Height ^ 2)
TextBox3.Text = Bmi_value
Select Case Bmi_value
Case 0.0 To 18.5
TextBox4.Text = "Underweight"
Case 18.6 To 24.9
TextBox4.Text = "Normal"
Case 25.0 To 29.9
TextBox4.Text = "Overweight"
Case Is >= 30.0
TextBox4.Text = "Obese"
End Select
End Sub
This is your code fixed:
'You were using Integer instead of Double
Dim Weight, Height, Bmi_value As Double
If you want to take the value from the textBoxes, you have to covert it to Double.
Weight = Convert.ToDouble(TextBox1.Text)
Height = Convert.ToDouble(TextBox2.Text)
'Better to call the right function Math.Pow()
Bmi_value = (Weight / Math.Pow(Height, 2))
'You have to convert it to String
TextBox3.Text = Convert.ToString(Bmi_value)
Select Case Bmi_value
Case 0.0 To 18.5
TextBox4.Text = "Underweight"
Case 18.6 To 24.9
TextBox4.Text = "Normal"
Case 25.0 To 29.9
TextBox4.Text = "Overweight"
Case Is >= 30.0
TextBox4.Text = "Obese"
End Select
End Sub
There was alot of error in this code:
First: don't declare var as integer if you need decimal value, like with the BMI calculation.
Second: always convert your value to the right type if you are getting them from TextBox or if you want to print them inside a TextBox
Dim dblWeight As Double, dblHeight As Double, dblBMI As Double
dblWeight = CDbl(TextBox1.Text) 'assumes lbs.
dblHeight = CDbl(TextBox2.Text) 'assumes inches
On Error GoTo 0
dblBMI = ((dblWeight * 703.0#) / (dblHeight * dblHeight))
TextBox3.Text = dblBMI
Select Case dblBMI
Case Is <= 18.5 : TextBox4.Text = "Underweight"
Case 18.6 To 24.9 : TextBox4.Text = "Normal"
Case 25.0# To 29.9 : TextBox4.Text = "Overweight"
Case 30.0# To 34.9 : TextBox4.Text = "Obese Class I"
Case 35.0# To 39.9 : TextBox4.Text = "Obese Class II"
Case Is >= 40.0# : TextBox4.Text = "Obese Class III"
End Select
Exit Sub
Try this, Works for me.

Two balance won't add up if both checkboxes are checked

I am writing a program that should calculate the balance with the given information (Which checkbox they choose (Savings (7%), Corporate(5%), or both, then the year they choose (2015, 2016, 2017), and lastly the amount they put in when cued to enter balance (And that is based on what type of account they choose in the first step). I have gotten all of the totals to show up correctly, except for when they choose both account types (Savings and Corporate). To me their should be a line that just adds the two totals if both are chosen, but that isn't the case. At least for me it isn't.
The total I get if I enter the balance of $2000 for savings and choose year 2015 the total is $2289.80 which is correct and then if I choose 2015 for the corporate account and enter $1000 the total is $1102.50. So if I chose both of the accounts and entered the same numbers but checked both checkboxes I get $3434.70, but I should get $3392.30!
Here is the code I have, any help would be much appreciated! ( I think it might literally be just one line of code and it is killing me!)
Public Class Form1
Private Sub btnMediaEstimatedFund_Click(sender As Object, e As EventArgs) Handles btnMediaEstimatedFund.Click
Dim interestRate, initialBalanceSavings, initialBalanceCorporate, finalBalance, year, theYear, subTotal As Double
Dim savingsInterestRate As Double = 0
Dim corporateInterestRate As Double = 0
Dim savingsSubTotal As Double = 0
Dim corporateSubTotal As Double = 0
txtBoxEstimatedBudget.Enabled = False
txtBoxAgenciesNeeded.Enabled = False
If radButtonTraditional.Checked Then
txtBoxAgenciesNeeded.Text = 3
ElseIf radButtonEMedia.Checked Then
txtBoxAgenciesNeeded.Text = 2
End If
If checkBoxSavings.Checked Then
savingsInterestRate = 0.07
ElseIf checkBoxCorporate.Checked Then
corporateInterestRate = 0.05
End If
If checkBoxSavings.Checked = False And checkBoxCorporate.Checked = False Then
MsgBox("Please chose an account type to proceed!", MsgBoxStyle.Critical, "Error")
End If
If radButton2015.Checked Then
theYear = 2015
ElseIf radButton2016.Checked Then
theYear = 2016
ElseIf radButton2017.Checked Then
theYear = 2017
End If
Dim inputtedData As String
If checkBoxSavings.Checked Then
Do
inputtedData = InputBox("Please enter a balance for SAVINGS account between $500.00 and $3000.00", "Initial Savings Balance", "0.00")
If inputtedData = "" Then
MsgBox("User chose to cancel calculation!")
Exit Sub
Else
initialBalanceSavings = CType(inputtedData, Single)
If initialBalanceSavings > 3000 Or initialBalanceSavings < 500 Then MsgBox("Please enter a balance for SAVINGS account equal to or above $500.00 and no more than $3000.00", MsgBoxStyle.Critical, "Error")
End If
Loop Until initialBalanceSavings >= 500 And initialBalanceSavings <= 3000
End If
If checkBoxCorporate.Checked Then
Do
inputtedData = InputBox("Please enter a balance for CORPORATE account between $500.00 and $3000.00", "Initial Corporate Balance", "0.00")
If inputtedData = "" Then
MsgBox("User chose to Cancel calculation!")
Exit Sub
Else
initialBalanceCorporate = CType(inputtedData, Single)
If initialBalanceCorporate > 3000 Or initialBalanceCorporate < 500 Then MsgBox("Please enter a balance for CORPORATE account equal to or above $500.00 and no more than $3000.00", MsgBoxStyle.Critical, "Error")
End If
Loop Until initialBalanceCorporate >= 500 And initialBalanceCorporate <= 3000
End If
savingsSubTotal = initialBalanceSavings
corporateSubTotal = initialBalanceCorporate
For year = 2013 To theYear - 1
If savingsInterestRate > 0 Then
savingsSubTotal = savingsSubTotal * (1 + savingsInterestRate)
End If
If corporateInterestRate > 0 Then
corporateSubTotal = corporateSubTotal * (1 + corporateInterestRate)
End If
Next
finalBalance = savingsSubTotal + corporateSubTotal
txtBoxEstimatedBudget.Text = FormatCurrency(finalBalance)
End Sub
I believe the erroneous logic is in this block of code:
finalBalance = initialBalanceSavings + initialBalanceCorporate
For year = 2013 To theYear - 1
subTotal = finalBalance * (1 + interestRate)
finalBalance = subTotal
Next
Combined with this block of code:
If checkBoxSavings.Checked Then
interestRate = 0.07
ElseIf checkBoxCorporate.Checked Then
interestRate = 0.05
End If
In the above, even if something checks both checkboxes the interest rate is set at 0.07 so in your loop if someone calculates 2015 you will do something like give you a final total of: 3000 * 1.07 * 1.07, whereas you really want (2000 * 1.07 * 1.07) + (1000 * 1.05 * 1.05)
In essence because you only use one variable to hold the interest rate (as well as only having one variable to hold sub-totals) your code cannot account properly for a scenario where someone selects both accounts. I would suggest having 2 variables to hold the interest rates:
Dim savingsInterestRate as Double = 0
Dim corporateInterestRate as Double = 0
And 2 variables to hold the sub-totals:
Dim savingsSubTotal as Double = 0
Dim corporateSubTotal as Double = 0
And in your For loop do:
savingsSubTotal = initialBalanceSavings
corporateSubTotal = initialBalanceCorporate
For year = 2013 To theYear - 1
If savingsInterestRate > 0 Then
savingsSubTotal = savingsSubTotal * (1 + savingsInterestRate)
End If
If corporateInterestRate > 0 Then
corporateSubTotal = corporateSubTotal * (1 + corporateInterestRate)
End If
Next
finalBalance = savingsSubTotal + corporateSubTotal
And change your interest rate check to:
If checkBoxSavings.Checked Then
savingsInterestRate = 0.07
End If
If checkBoxCorporate.Checked Then
corporateInterestRate = 0.05
End If
So you can account for the person's selection (using the ElseIf means that if they check both, it will discard the corporate rate since checkBoxSavings.Checked is already true sp it never falls into the ElseIf block)

Visual Basic - "If" Statements Not Showing Result In Label

I'm working on an assignment where the program needs to calculate and display the total cost for shipping a package, based on weight and whether it is being shipped to Continental U.S., Alaska, or Hawaii. When I click the Calculate button, though, the label that is supposed to display the total is left blank. I've looked through this and tried placing the calculation in different parts/at the end of the "If" statements. Here's what I have thus far, any help would be appreciated:
Dim decWeight As Decimal
Dim decTotalCost As Decimal
Dim decDestination As Decimal
Dim decRate As Decimal
If IsNumeric(txtWeight.Text) Then
decWeight = Convert.ToDecimal(txtWeight.Text)
If decWeight <= 30 > 0 Then
If radContinental.Checked Then
decDestination = 1
ElseIf radHawaii.Checked Then
decDestination = 1.2
ElseIf radAlaska.Checked Then
decDestination = 1.26
End If
If decWeight <= 2 Then
decRate = 3.69
ElseIf decWeight <= 4 > 2 Then
decRate = 4.86
ElseIf decWeight <= 6 > 4 Then
decRate = 5.63
ElseIf decWeight <= 8 > 6 Then
decRate = 5.98
ElseIf decWeight <= 10 > 8 Then
decRate = 6.28
ElseIf decWeight <= 30 > 10 Then
decRate = 15.72
End If
decTotalCost = decRate * decDestination
lblTotalCost.Text = decTotalCost.ToString("C")
ElseIf decWeight <= 0 Then
MsgBox("Please Enter a Positive Weight.", , "Input Error")
ElseIf decWeight > 30 Then
MsgBox("You Have Entered " & decWeight.ToString() & ". Please Enter a Weight Under 30 Pounds", , "Input Error")
End If
ElseIf txtWeight.Text = "" Then
MsgBox("Please Enter the Weight", , "Input Error")
Else : MsgBox("Please Enter a Number", , "Input Error")
End If
You should try this if statement: If decWeight <= 30 and decWeight > 0 Then
This will check if the decWeight is less than or equal to 30 and make sure that it is 'non-zero' Hope this helps :-)

Problem involving salesperson

Okey my question is when you run this you do not get no dollar amount in the monthly catergory Can someone tell me what I am doing wrong.Cause if you type in allen for name and code 1 monthly sales should be 500 and commission should be 1005. I just can not figure out what I am doing wrong.
Option Strict On
Option Explicit On
Module Module1
Sub Main()
Dim salesPersonName As String
Dim monthlySales, SalesPersonCommission, salesmancode As Integer
Dim totalSales, totalCommission As Integer
Console.WriteLine("Please enter your name: ")
salesPersonName = Console.ReadLine()
Do While Not (salesPersonName.Equals("Eugene"))
Console.WriteLine("Please enter a sales code: ")
salesmancode = CInt(Console.ReadLine())
Select Case salesmancode
Case 1
SalesPersonCommission = CInt(0.01 * monthlySales + 1000)
Case 2
SalesPersonCommission = CInt(0.03 * monthlySales)
Case 3
SalesPersonCommission = CInt(0.04 * monthlySales + 500)
Case Is < 3
SalesPersonCommission = CInt(0.02 * monthlySales + 200)
End Select
totalCommission = monthlySales + totalSales
Console.WriteLine("Please enter your name= " & salesPersonName)
Console.WriteLine("Monthly Sales= " & monthlySales)
Console.WriteLine("Sales Code= " & salesmancode)
Console.WriteLine("Sales Person Commission= " & SalesPersonCommission)
Console.WriteLine("Please enter your name:")
salesPersonName = Console.ReadLine()
Loop
Console.WriteLine("Total Commission Dollars= " & monthlySales + totalSales)
End Sub
End Module
You're not assigning an amount to monthlySales before using it in the calculation.
Perhaps you mean to use those:
Select Case salesmanCode
CASE 1
monthlySales = 500
....
End Select
SalesPersonCommission = CInt(0.01 * monthlySales + 1000)
Depending on what exactly you're trying to do, you may want to surround part of your calculation in parentheses to indicate clearly what order you want the calculations to occur. The first calculation below gives a different result than the second:
SalesPersonCommission = CInt(0.01 * (monthlySales + 1000))
SalesPersonCommission = CInt((0.01 * monthlySales) + 1000)
The second is what you want.
It looks like you're forgetting to set monthlySales.
If you set it to 500 you get the results you say you're expecting.