Need help correcting this VB.net - vb.net

Dim dbBorrow As Double
dbBorrow = txtBorrow.Text
If dbBorrow < 500000 Then
MessageBox.Show("Lowest Amount which can be borrow is RS.500000")
ElseIf dbBorrow > 7000000 Then
MessageBox.Show("Maximum amount which can be borrowed is RS.7000000")
ElseIf dbBorrow = "" Then
MessageBox.Show("Pls Enter the amount you want to borrow")
My question says that if i want to obtain a loan the val should be inbetween 500000 and 7000000, so if its less than 500000 then i used a message box to say the loan cannot be obtain i used the same thing for more than 70000000. but if the textbox is left empty i wanted to display a message saying pls enter a val. i tried this error appears "Conversion from string "" to type 'Double' is not valid."

You are mixing strings and double. You should enable option strict on, this will help you understand what is happening.
If you properly convert your string to a double, you can set your double to NaN if it's not a valid number (this won't just work for empty string, but also work if you write letters).
Dim dbBorrow As Double
If Not Double.TryParse(txtBorrow.Text, dbBorrow) Then
dbBorrow = Double.NaN
End If
If dbBorrow < 500000 Then
MessageBox.Show("Lowest Amount which can be borrow is RS.500000")
ElseIf dbBorrow > 7000000 Then
MessageBox.Show("Maximum amount which can be borrowed is RS.7000000")
ElseIf Double.IsNaN(dbBorrow) Then
MessageBox.Show("Pls Enter the amount you want to borrow")
Else
' ...
End If

I made a few adjustments to your code please see below... Using the TryParse will not thrown an exception when not a double, it would return false...
Dim dbBorrow As Double = 0
If Double.TryParse(txtBorrow.Text, dbBorrow) Then
If dbBorrow < 500000 Then
MessageBox.Show("Lowest Amount which can be borrow is RS.500000")
ElseIf dbBorrow > 7000000 Then
MessageBox.Show("Maximum amount which can be borrowed is RS.7000000")
End If
Else
MessageBox.Show("Pls Enter the amount you want to borrow")
End If

Related

I wrote a VBA code to input data, but it doesn't work for decimals

So this is the code, which works only for integers
Dim CoupRate As Double
Do
CoupRate = InputBox("enter coupon rate in percent without % sign. It must be between 0.00% and 25.00%")
If CoupRate < 0 Or CoupRate > 25 Then
MsgBox ("CoupRate must be between 0% and 25%")
Else
Exit Do
End If
Loop
Please Use Comma , instead of dot .
I was able to get the decimals in the output as well. Could you please be more specific.
CoupRate = InputBox("enter coupon rate in percent without % sign. It must be between 0.00% and 25.00%")
If CoupRate < 0 Or CoupRate > 25 Then
MsgBox ("CoupRate must be between 0% and 25%")
Else
'Exit Do
MsgBox CoupRate & "%"
End If

Excel & VBA: 'If value is less than 1' condition being triggered by a value that is exactly 1

I've encountered a baffling behaviour in Excel VBA that I'm trying to understand and wondered if anyone can point me in the direction of the explanation please?
Background - I've inherited a reporting tool that is used to calculate whether there is enough remaining allowance of holiday each day to allow an additional holiday to be taken. I found that it is behaving unexpectedly when the remaining allowance is exactly '1'.
Below was the VBA as it already existed (the values of the variables in the real file are set by other queries but I've set them manually here in order to replicate the issue). With this code, the message box is triggered even though the result of (Total * Allowance) - Taken is exactly 1 and the 'If' condition should only be met by values less than 1
Dim Total As Double
Dim Allowance As Double
Dim Taken As Double
Total = 20
Allowance = 0.15
Taken = 2
If (Total * Allowance) - Taken < 1 Then
MsgBox "Not Enough Allowance Remaining"
End If
I tried changing the code to the below and found that when 'remaining' is declared as 'double' datatype, the same issue occurs. However if I change the datatype of 'remaining' to 'single', the code behaves as expected and the message box is not displayed:
Dim Total As Double
Dim Allowance As Double
Dim Taken As Double
Dim Remaining As Double
Total = 20
Allowance = 0.15
Taken = 2
Remaining = (Total * Allowance) - Taken
If Remaining < 1 Then
MsgBox "Not Enough Allowance Remaining"
End If
I reasoned it must be something to do with the way Excel / VBA handles the value '1' in different data types and some searching turned up the articles below but I'm unsure if I'm on the right track or am missing a simpler answer - any ideas please?
Article 1
Article 2
Thanks
This is a simple rounding problem. This works:
Sub dural()
Dim Total As Double
Dim Allowance As Double
Dim Taken As Double
Total = 20
Allowance = 0.15
Taken = 2
If ((Total * Allowance) - Taken) < 0.999999 Then
MsgBox "Not Enough Allowance Remaining"
End If
End Sub
Because the floating point arithmetic does not yield exactly 1For example:
Sub dural()
Dim Total As Double
Dim Allowance As Double
Dim Taken As Double
Total = 20
Allowance = 0.15
Taken = 2
If (Total * Allowance) - Taken < 0.999999 Then
MsgBox "Not Enough Allowance Remaining"
End If
MsgBox 1 - ((Total * Allowance) - Taken)
End Sub
Produces:
This is a known and well documented "issue" with Excel. As summarized here: https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft_Excel
"As with other spreadsheets, Microsoft Excel works only to limited accuracy because it retains only a certain number of figures to describe numbers (it has limited precision). [...] Although Excel can display 30 decimal places, its precision for a specified number is confined to 15 significant figures, and calculations may have an accuracy that is even less due to three issues: round off, truncation, and binary storage."
So, if you change your second code snippet to the following:
Dim Total As Double
Dim Allowance As Double
Dim Taken As Double
Dim Remaining As Double
Total = 20
Allowance = 0.15
Taken = 2
Remaining = (Total * Allowance) - Taken
If Remaining < 1 Then
MsgBox 1 - Remaining
End If
You will come to realize that the inaccuracy starts (exactly as described above) at the 15th decimal place. For more samples and a more elaborate analysis you might also want to have a look at the following post: http://www.cpearson.com/excel/rounding.htm
You are absolutely correct that the data types are the issue.
The problem is (basically) that Double can't represent certain numbers accurately (though they can do it very precisely), because of the peculiarities of how floating point types encode the numbers they represent (basically: as a number raised to a power).
If you're dealing with decimal data, or currency data, you're probably best off using a fixed precision type, like Currency, rather than Double, which is going to provide a guaranteed level of precision (currency is both precise and accurate to 4 decimal places).
If you need greater precision than 4 decimal places, using a Variant is probably your best bet, and coercing it to a decimal:
Dim Total As Variant
Dim Allowance As Variant
Dim Taken As Variant
Total = CDec(20)
Allowance = CDec(0.15)
Taken = CDec(2)
If (Total * Allowance) - Taken < 1 Then
MsgBox "Not Enough Allowance Remaining"
End If
(The coercion will probably happen implicitly, but if you're paranoid, CDec() will force it.)

Excel VBA: Case query

I have this code, which sorts an input number into a convenient range:
Public Sub TestCase2()
Dim Number As Long
Dim Message As String
Number = InputBox("Enter a number:", "Number entry")
Message = "Number is "
Select Case Number
Case Is < -10
MsgBox (Message & "less than -10")
Case Is < 0
MsgBox (Message & "equal to or greater than -10 but less than zero")
Case Is = 0
MsgBox (Message & "equal to zero")
Case Is < 10
MsgBox (Message & "greater than zero but less than 10")
Case Else
MsgBox (Message & "greater than or equal to 10")
End Select
End Sub
It falls over when I enter -10.5 - I would have thought it would output:
Number is less than -10
But it says:
Number is equal to or greater than -10 but less than zero.
If I enter -10.6, the output is as expected: Number is less than -10.
Also, it falls over with an entry of 0.001: it says Number is equal to zero. Which it isn't.
I cannot work with integers here - the input has to have decimals (up to 3).
Is there a neater way of doing this? Many thanks for your constructive input.
Regards,
Shane (VBA newbie of 4 weeks).
PS I know I can do this with If-Then statements, but I'm just getting to grips with Select Case-Case Else).
InpuBox function returns string. So, to be able to compare value returned by this function, you need to convert it into proper numeric format:
Dim sNumber As String
sNumber = InputBox(...)
'prevent Cancel click
If sNmber = "" Then Exit Sub
'prevent non-numeric value
If Not IsNumeric(sNmber) Then Exit Sub
Select Case CDbl(sNumber)
....
If you want to use If .. else statement instead of Select case , please see: If .. Then ... Else ...
Number may have to be dimmed as Single or Double
Dim Number As Single

VB - Negative Number and Conditional Statement

Back again with another noob question that is bugging the crap out of me. I spent 2 days trying figure this one out. It seems that me and VB and negative numbers always have a misunderstanding.
I got everything else in the program for a fat percentage calculator to work except the conditional statement that SHOULD print out an error message if either the double conversion of two textbox strings is less than zero. However, even though I enter negative numbers for both when testing, the program skips over my Else error statement and calculates the two negative numbers anyway and gets some wholly ridiculous fat percentage number. It doesn't even seem as if it's just going through with the expressions if the "If-Then" part of the code as I did the math and the percentage answer does not match up.
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'Declare variables
Dim dblCaloriesInFood As Double
Dim dblGramsOfFat As Double
Dim dblPercentageOfCaloriesFromFat As Double
Dim dblCaloriesFromFat As Double
'Always initialize lblLowInFat message as not visible when button is clicked
lblLowInFat.Visible = False
Try
'Converting textbox strings to double.
dblCaloriesInFood = CDbl(txtCaloriesInFood.Text)
dblGramsOfFat = CDbl(txtGramsOfFat.Text)
If dblCaloriesInFood Or dblGramsOfFat > 0 Then
'Calculate Calories from fat
dblCaloriesFromFat = dblGramsOfFat * 9
'Calculate percentage of calories from fat
dblPercentageOfCaloriesFromFat = dblCaloriesFromFat / dblCaloriesInFood
'Display percentage of calories from fat
If dblPercentageOfCaloriesFromFat >= 0 Then
lblMessage.Text = dblPercentageOfCaloriesFromFat.ToString("p")
Else
lblMessage.Text = String.Empty
End If
'Display low fat message
If dblPercentageOfCaloriesFromFat <= 0.3 And dblPercentageOfCaloriesFromFat > 0 Then
lblLowInFat.Visible = True
End If
Else
'really tried to make this message work but couldn't figure it out.
'why does it only display this message when zero is entered and not when
'negative numbers are entered. instead it just calculates the negative numbers
'as if they were whole positive numbers or something, not sure because the percentage
'is way off the charts when i enter negative numbers. can't figure this out.
MessageBox.Show("Either the calories or fat grams were incorrectly entered")
txtCaloriesInFood.Text = String.Empty
txtGramsOfFat.Text = STring.Empty
txtCaloriesInFood.Focus()
End If
Catch
'error message for invalid input
MessageBox.Show("Please enter a numeric value for calories in food & number of fat grams.")
txtCaloriesInFood.Focus()
End Try
End Sub
Your If statement is wrong. First, you need to test the two values separately. Second, you want both values to be greater than zero, so you should use And instead of Or (which means only one has to be greater than zero).
If dblCaloriesInFood > 0 And dblGramsOfFat > 0 Then

Displaying "amount paid" was not enough on Change Calculator, VB VS2012

I am new to VB and for a class project we are to make a change calculator, similar to the one that a question was asked on here before. I have an amount owed and amount paid label and textbox. If the amount owned is greater than the amount paid, the program should display message to remind the customer and tell them how much more to pay.
I figured it out, but the amount that is still due that is displayed in the message is -1.
Example:
Amount Owed: 25
Amount Paid:10
The message will read, The amount paid is less than what is owed. Please pay $ -1 more.
I'm not sure what I've done wrong, and I'm stuck. Any help will be appreciated!
Option Strict On
Option Explicit On
Public Class Form1
Dim AmountPaid As Double
Dim AmountOwed As Double
Private Sub CalculateButton_Click(sender As Object, e As EventArgs) Handles CalculateButton.Click
'input amount owed from OwedMaskedTextBox
'input paid amount from PaidTextBox
AmountOwed = Convert.ToDouble(OwedTextBox.Text)
AmountPaid = Convert.ToDouble(PaidTextBox.Text)
'calculate difference of amount owed and paid
'display an alert message if paid amount is less than what is owed
Dim dif As Double
Dim result As Double = 0
result = CDbl(AmountPaid < AmountOwed)
dif = AmountPaid - AmountOwed
If CBool(result) Then
AlertLabel.Text = "Amount paid is less than what is owed." &
"Please pay $ " & result & " more."
Else
AlertLabel.Text = ""
End If
'display the result
'let totallabel change text to display the difference
TotalLabel.Text = "Change: " &
dif.ToString()
End Sub
End Class
Change the code in this way
'calculate difference of amount owed and paid
'display an alert message if paid amount is less than what is owed
Dim result As Boolean
result = (AmountPaid < AmountOwed)
dif = AmountPaid - AmountOwed
If result Then
.....
The expression (AmountPaid < AmountOwed) is a boolean expression and you could assign directly to a boolean variable. Then you could test this boolean before displaying your message.
So there is no need of these conversions that introduce errors.