Error on comparison of numbers from textbox - vba

I have 2 textboxes which inputs 2 values from the user and compares the first value with the second. If the first value is less than the second value, it enters the loop where the user has to input the values again.
The problem I am getting is if I input 10 and 9.9 in the text boxes, it is entering into the loop and saying that 10 is less than 9.9. This happens only with 10,100 and 1000. Please help.
I even tried defining Long type variables for both the integers and assigned them and compared them, excel just hangs. Please help
Here is the code below.
If Mean < LSLValue Then
MsgBox "Please enter a numeric value greater than LSL as Nominal Value"
Me.DimnTxt.Value = InputBox("Enter the Nominal")
Me.LSLTxt.Value = InputBox("Enter the LSL")
Mean = Me.DimnTxt.Value
LSLValue = Me.LSLTxt.Value
End If
Loop Until Mean >= LSLValue

May be because you are comparing text instead of number.
Try convert to number then compare. EG:
if CDbl(Textbox1.value) < CDbl(Textbox2.value) then
'....
end if

Related

Forcing user to enter one entry from two options not to write it together

i have two text boxes : percentage and txtamount
i want to force user to enter percentage or amount not to write it together
casue if he did entered % and amount it makes some problems with me as i have alot of formulas
thanks
What I have tried:
privite sub post_click()
If (Me.percentage.Value >= 0 And Me.txtamount.Value >= 0) Then MsgBox " You should select % or amount ": Exit Sub
If you want to ensure that one (and only one) of your two textboxes has a value in it, use the following:
Private Sub post_Click()
If Not (Me.percentage.Value = "" Xor Me.txtamount.Value = "") Then MsgBox "You should select % or amount": Exit Sub
Testing for >= 0 won't work if the textbox is empty (because "" >= 0 will give a type mismatch). Testing for whether the textbox is "" will give a better indication of whether data has been entered.
Using Xor (which returns True iff one operand is True and the other is False) will therefore determine whether only one textbox has been filled in and the other left empty, and the Not will display the message if that is not the case.

Textbox value summation

I have two textboxes in which users enter a number, Data1.text and Data2.text. I need to do a simple check before proceeding and closing a form, i.e. the process should check if the sum of the values in Data1 and Data2 textbox is greater or lesser than the value from a label text named FinalValue.text, which gets its value from my main form.
If Data1.Text + Data2.Text <> FinalValue.Text Then
MessageBox.Show("The sum of the entered values are different from the final value!")
Exit Sub
End If
The problem is that whatever the user enters in the two textboxes, the messagebox pops up.
For example...if the FinalValue label has a value of 58.50, and if the user enters in one textbox 50 and in the other one 8.50, the messagebox pops up. I suppose I have to format my textboxes or something like that, but not sure in which way.
Thanks,
When you do Data1.Text + Data2.Text, you are actually just concatenating the values, not doing a number Sum, you need to convert to decimal.
Something like :
If Decimal.Parse(Data1.Text) + Decimal.Parse(Data2.Text) <> Decimal.Parse(FinalValue.Text) Then
MessageBox.Show("The sum of the entered values are different from the final value!")
Exit Sub
End If
Assuming the values are integers , change your condition to match the integers sum, You are currently concatenating the strings
CInt(Data1.Text) + CInt(Data2.Text) <> CInt(FinalValue.Text)
Or for Decimals use Decimal.Parse() in place of CInt()

How does one subtract the .Value from the Offset.Value of any given 'i' in a For Each loop?

I have the following code written in VBA:
For Each W In Range("B5:B15000").Cells
If W.Offset(-1, 0).Value - W.Value > 1.5 Then
W.Offset(-1, 0).EntireRow.Delete
End If
Next W
The intent is to iterate down 'Column B', between Rows 5 and 15000, subtracting each of the current 'W' values from the Offset 'W' values. If the resultant difference from the equation is greater than 1.5 then delete the entire following 'W'(Offset) row. If the difference is less than or equal to 1.5, move on to the next 'W'.
For a better understanding of the data set, column B is essentially a time stamp series. As you go further down the column, the time stamp increases in varying amounts of seconds. I need to pick out the gaps (so to speak) that are greater than 1.5 seconds and delete them.
Here is a sample of the column data:
The task seems simple enough, but I am receiving a 'Type Mismatch' error. I am relatively new to the For Each loop, so I do not quite understand what portions are mismatched.
The formats are definitely numbers, so you shouldn't get a type mismatch. My guess is row 5 is the first row which contains data so offsetting by -1 to row 4 causes the error because you cannot subtract a string (the header text) and number.
This aside, your logic of going top down could present a problem (in addition the implementation problem of deletion of the iterator, W, modifying the collection). Consider this data:
12
13
15
16
17
Going top down would delete row 3 and then compare row 4 to row 2 (since 3 was deleted) and delete it is well since the difference is larger than 1.5 (and so on).
Instead you will want to go bottom up. In the above example, row 5 and row 4 would remain because they would be compared with respect to their intended value with row 3 still being deleted.
The code for that could look something like this:
Dim i As Long
For i = 15000 to 6 Step -1 '6 because 6-1 would mean 5 is the first row which contains data.
If Cells(i - 1, "B").Value - Cells(i, "B").Value > 1.5 Then
Rows(i).Delete
End If
Next
Edit: Going bottom up is still going to leave large gaps in your data. For example in your provided data the following (among others) would be deleted:
50
31
23
A Type Mismatch error is due to a value that isn't the type you think it is. Most likely, one of the cells is blank, or contains text, or something that's not a number.
Explicit conversion to a Double with CDbl will likely not fix the Type Mismatch error, because if either value is not a number, things go boom anyway - implicit conversion or not.
The right thing to do is to handle all the edge cases - you need to decide how to handle values that are not a number - here's a function that treats them as 0:
Private Function GetNumericValue(rng As Range) As Double
Dim result As Double
On Error Resume Next
result = CDbl(rng.Value)
If Err.Number <> 0 Then result = 0
On Error GoTo 0
GetNumericValue = result
End Function
Now you can do this:
If GetNumericValue(W.Offset(-1, 0)) - GetNumericValue(W.Value) > 1.5 Then
If that still doesn't fix it, and your data is completely made of what appears to be numbers, then my bet is on the decimal separator character being off. Verify that in Control Panel / Regional Settings. Your spreadsheet seems to be expecting a dot, but your settings might have it as a comma.

while entering more than 10 digit numeric validation in grid view not working

I have a grid view ,,in grid view 5 th and 6 th column i have only enter numeric data,i mean mobile number and land number ,
i given code like this in gridview_cellvalidating event
If e.ColumnIndex = 5 Or e.ColumnIndex = 6 Then
Dim i As Integer
If Not String.IsNullOrEmpty(e.FormattedValue) AndAlso Not Integer.TryParse(Convert.ToString(e.FormattedValue), i) Then
e.Cancel = True
MsgBox("Please Enter Numeric")
Else
End If
End If
but this code is working if i enterd only 10 digit number,in 6 th column of datagrid view i have to enter country code also 'So i am giving number somthing like this: 971563158147.
this number is coming more than 10 digit,so this time showing message box("Please Enter Numeric")
how i can resolve this issue?
If you want to only allow all-numeric input up to, say, 12 characters, and don't actually care about parsing it as a number, you could use regular expressions. Pseudo-code:
Imports System.Text.RegularExpressions
Regex regex = new Regex(#"\d{12}");
If Not String.IsNullOrEmpty(e.FormattedValue) AndAlso Not regex.IsMatch(e.FormattedValue)
This will ensure that you get a non-empty input which is composed of exactly 12 digits. Now, if you wanted to allow, say, between 8 to 12 digits, you would just change the regex to:
Regex regex = new Regex(#"\d{8,12}");
To address your original query, 971563158147 is larger than the maximum value for Int32, so there will be overflow when parsing it. That's the source of your error.
You are running into the maximum value for an Integer when the input number is larger than 2,147,483,647.
You could instead use a regular expression to validate the input or use Int64.TryParse.
Check the MaxInputLength of the 6th cell, change it to required length if the field holds 10

How can I check string in textbox as integer in Visual Basic?

I have 3 textboxes (day, month, year) and I want to check if input is e.g. day has to be from 1 to 31 and so on.
My code is:
If InputDan.Text < "1" Or InputDan > "31" Then Warning.Text = "Not a valid day input." Else Warning.Text = ""
Also I have day and month input limited to 2 characters and year to 4.
It works fine with numbers from 10 to 31 and it properly puts an warning message when input is 0 or 32 and on.
Here's the problem...
When I put in numbers from 4 to 9 it puts on a warning message, as I figured out later that program considers empty space after one character input as 0.
So if I enter 4 the program will read it as 40, and so on.
Can I solve this problem with converting String input as Int somehow?
You need to parse the numbers to integer before you can compare them, otherwise >"11" will compare them alphabetically and not by their numerical order.
Dim day As Integer
Dim valid As Boolean = Int32.TryParse(InputDan.Text, day)
Now you know if that input was a correct number and you could show a warning if it was not.
I would suggest a different approach to check whether or not the input was a correct day since you must take the number of days in that month into account(also leap years, different calendars etc). So use the current culture's calendar and look if the number of days is correct for the given month in this way:
Dim daysInMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year, month)
If day > daysInMonth OrElse day < 1 Then
' show warning '
End If
(assuming you have already checked the year and month part with Int32.TryParse)
Better than doing this from the code behind, asp.net has already validations here is an example of a textbox that represents the day, and it has to be between 1 and 31:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ErrorMessage="You have to insert a valid day" ControlToValidate="TextBox2" MaximumValue="31" MinimumValue="1"></asp:RangeValidator>
check it out
Your problem is, that "9" (the string) IS "larger" than "31". Because sorting is done on the first char, then the second and so on.
Dim Value As Integer
' is there an (integer) NUMBER in the textbox?
If Integer.TryParse(InputDan.Text, Value) Then
If Value > 0 AndAlso Value < 31 Then
' do something
Else
MessageBox.Show("please enter a number!")
End If
Else
MessageBox.Show("please enter a number!")
End If
With "TryParse" you can test if a String can be converted to an Integer (or Double, Single, whatever implements a TryParse method) and if it can be converted, the value is stored in the second parameter.
You should use Strict on" to avoid the coding problems - basically you are comparing strings against each other. They do NOT behave like Integers for comparisons.
Try like this: (Assuming framework above/or 3.5)
If Not IsNumeric(InputDan.Text) OrElse _
Not Enumerable.Range(1, 31).Contains(CInt(InputDan.Text)) Then
Warning.Text = "Not a valid day input."
Else
Warning.Text = ""
End If
It will first validate the input must be a number and then will validate if it lies within range of 1 and 31. I assume Days can not be 1.5 so I called CInt.
OrElse is what we call ShortCircuit. The second condition will not evaluate if the first one failed.