checking if string is numeric is not working in vb - vb.net

I am trying to check if a string is numeric but in vain. here is my code:
If Val(fnumField.Text.Trim) > 0 Or fnumField.Text.Trim = "0" Or Val(phnField.Text.Trim) > 0 Or phnField.Text.Trim = "0" Or Val(ophnField.Text.Trim) > 0 Or _
ophnField.Text.Trim = "0" Or Val(treeField.Text.Trim) > 0 Or treeField.Text.Trim = "0" Then
messageBox.Show("number")
Else
messageBox.Show("not number")
EndIf
The problem I have is that when I run the program and insert a character string like "abcd" in one of the textfields like "fnumField", it still executes the code in the "if" and not in the "else". What am I not doing right?

try this:
If (Val(fnumField.Text.Trim) > 0 Or fnumField.Text.Trim = "0") And (Val(phnField.Text.Trim) > 0 Or phnField.Text.Trim = "0") And (Val(ophnField.Text.Trim) > 0 Or
ophnField.Text.Trim = "0") And (Val(treeField.Text.Trim) > 0 Or treeField.Text.Trim = "0") Then
messageBox.Show("number")
Else
messageBox.Show("not number")
EndIf

Related

Is there a way to maintain the length of a user entered number, to prevent removal of extra 0's?

I'm creating a Diabetes management algorithm, and I'm trying to find a way for the user's entered time blocks to be maintained at 4 digits
I've been searching on google, but all I have been able to find is how to check the length of a variable, which I already know how to do.
Sub timeBlocks()
Dim file As String = "C:\Users\Connor\Documents\Visual Studio 2017\Projects\meterCodeMaybe\TIMEBLOCKS.txt"
Dim blockNum As Integer
Console.WriteLine("Please be sure to enter times as a 24 hour value, rather than 12 hour, otherwise the input will not be handled.")
Console.Write("Please enter the amount of time blocks you require for your day: ")
blockNum = Console.ReadLine()
Dim timeA(blockNum - 1) As Integer
Dim timeB(blockNum - 1) As Integer
Dim sensitivity(blockNum - 1) As Integer
Dim ratio(blockNum - 1) As Integer
For i = 0 To (blockNum - 1)
Console.WriteLine("Please enter the start time of your time block")
timeA(i) = Console.ReadLine()
Console.WriteLine("Please enter the end time of your time block")
timeB(i) = Console.ReadLine()
Console.WriteLine("Please enter the ratio for this time block (Enter the amount of carbs that go into 1 unit of insulin)")
ratio(i) = Console.ReadLine()
Console.WriteLine("Please enter the insulin sensitivity for this time block
(amount of blood glucose (mmol/L) that is reduced by 1 unit of insulin.)")
sensitivity(i) = Console.ReadLine()
FileOpen(1, file, OpenMode.Append)
PrintLine(1, Convert.ToString(timeA(i)) + "-" + Convert.ToString(timeB(i)) + " 1:" + Convert.ToString(ratio(i)) + " Insulin Sensitivity:" + Convert.ToString(sensitivity(i)) + " per mmol/L")
FileClose(1)
Next
End Sub
Basically, I want the user to be able to enter a 4 digit number for their time block, to match a 24 hr time, so if they enter 0000, it is displayed as this, however, it removes all previous 0's and sets it to just 0.
Perhaps pad the number with 4 leading 0's:
Right(String(digits, "0") & timeA(i), 4)
Or as an alternative, store the value as a string so that it can be printed out in its original form.
I have written a Function to get a 24 hours format time from user, I hope it would help:
Public Function Read24HFormatTime() As String
Dim str As String = String.Empty
While True
Dim c As Char = Console.ReadKey(True).KeyChar
If c = vbCr Then Exit While
If c = vbBack Then
If str <> "" Then
str = str.Substring(0, str.Length - 1)
Console.Write(vbBack & " " & vbBack)
End If
ElseIf str.Length < 5 Then
If Char.IsDigit(c) OrElse c = ":" Then
If str.Length = 0 Then
' allow 0, 1 or 2 only
If c = "0" OrElse c = "1" OrElse c = "2" Then
Console.Write(c)
str += c
End If
ElseIf str.Length = 1 Then
If str = "0" Then
'allow 1 to 9
If c <> ":" Then
If CInt(c.ToString) >= 1 AndAlso CInt(c.ToString) <= 9 Then
Console.Write(c)
str += c
End If
End If
ElseIf str = "1" Then
'allow 0 to 9
If c <> ":" Then
If CInt(c.ToString) >= 0 AndAlso CInt(c.ToString) <= 9 Then
Console.Write(c)
str += c
End If
End If
ElseIf str = "2" Then
'allow 0 to 4
If c <> ":" Then
If CInt(c.ToString) >= 0 AndAlso CInt(c.ToString) <= 4 Then
Console.Write(c)
str += c
End If
End If
End If
ElseIf str.Length = 2 Then
'allow ":" only
If c = ":" Then
Console.Write(c)
str += c
End If
ElseIf str.Length = 3 Then
If str = "24:" Then
'allow 0 only
If c = "0" Then
Console.Write(c)
str += c
End If
Else
'allow 0 to 5
If c <> ":" Then
If CInt(c.ToString) >= 0 AndAlso CInt(c.ToString) <= 5 Then
Console.Write(c)
str += c
End If
End If
End If
ElseIf str.Length = 4 Then
If str.Substring(0, 3) = "24:" Then
'allow 0 only
If c = "0" Then
Console.Write(c)
str += c
End If
Else
'allow 0 to 9
If c <> ":" Then
If CInt(c.ToString) >= 0 AndAlso CInt(c.ToString) <= 9 Then
Console.Write(c)
str += c
End If
End If
End If
End If
End If
End If
End While
Return str
End Function
The user can only enter time like 23:59 08:15 13:10 and he couldn't enter formats like 35:10 90:00 25:13 10:61
This is a sample code to show you how to use it:
Dim myTime = DateTime.Parse(Read24HFormatTime())
Dim name = "Emplyee"
Console.WriteLine($"{vbCrLf}Hello, {name}, at {myTime:t}")
Console.ReadKey(True)

I can't figured out how do I properly place the code block of "IF statement"

All I want is to have the If statement code block properly be executed. Supposedly the idea was very simple.
On the quantity portion:
if it is not a number, it returns an error
else if it is a number which is above 0, message box "accepted"
else if the number is zero, then message box "quantity is 0"
else if the number is below zero, then message box "Error: quantity below zero"
However, when I try to run the program, when I try to input a number equals to RequestQuantity3TxtBx or below 0, it doesn't do anything at all.
If IsNumeric(RequestQuantityTxtBx.Text) Then
num1 = RequestQuantity2TxtBx.Text
num2 = RequestQuantityTxtBx.Text
total = num1 - num2
RequestQuantity3TxtBx.Text = total
If RequestQuantity3TxtBx.Text > 0 Then
If RequestQuantity3TxtBx.Text < 0 Then
If RequestQuantity3TxtBx.Text = 0 Then
MessageBox.Show("Quantity = 0")
Else
'------if quantity below 0
MessageBox.Show("Error: Quantity below 0")
End If
Else
'------if quantity is equals to 1
MessageBox.Show("Accepted")
End If
End If
Else
MessageBox.Show("ERROR")
End If
You could put some Validation in the TextBox to make sure that the user will enter a number instead of a character.
Private Sub RequestQuantityTxtBx_TextChanged(sender As Object, e As EventArgs) Handles RequestQuantityTxtBx.TextChanged
If Not IsNumeric(RequestQuantityTxtBx.Text) Then
MsgBox("This is not a number, please enter a number!")
End Sub
Private Sub RequestQuantity2TxtBx_TextChanged(sender As Object, e As EventArgs) Handles RequestQuantity2TxtBx.TextChanged
If Not IsNumeric(RequestQuantityTxtBx.Text) Then
MsgBox("This is not a number, please enter a number!")
End Sub
Then you can put the IF ELSE statement.
IF RequestQuantity3TxtBx.Text > 0 THEN
MsgBox("Accepted")
ELSEIF RequestQuantity3TxtBx.Text = 0 THEN
MsgBox("Quantity is 0")
ELSIF RequestQuantity3TxtBx.Text < 0 THEN
MsgBox("ERROR: Quantity below zero")
ELSE
MsgBox("ERROR: It's not a number")
END IF
OR you can just replace your code with this.
If IsNumeric(RequestQuantityTxtBx.Text) Then
num2 = RequestQuantityTxtBx.Text
IF IsNumeric(RequestQuantity2TxtBx.Text)
num1 = RequestQuantity2TxtBx.Text
total = num1 - num2
RequestQuantity3TxtBx.Text = total
IF RequestQuantity3TxtBx.Text > 0 THEN
MsgBox("Accepted")
ELSEIF RequestQuantity3TxtBx.Text = 0 THEN
MsgBox("Quantity is 0")
ELSE RequestQuantity3TxtBx.Text < 0 THEN
MsgBox("ERROR: Quantity below zero")
END IF
ELSE
MsgBox("ERROR: It's not a number")
END IF
ELSE
MsgBox("ERROR: It's not a number")
END IF
This code might be another option to full fill your requirement.
' Validate if the inputs are numeric
If IsNumeric(RequestQuantityTxtBx.Text) AndAlso IsNumeric(RequestQuantityTxtBx2.Text) Then
' Cast the input to double to accomodate decimal input
Dim num1 As Double = CType(RequestQuantityTxtBx.Text, Double)
Dim num2 As Double = CType(RequestQuantityTxtBx2.Text, Double)
' Sum the input and assign the resul to the RequestQuantityTxtBx3
Dim num3 As Double = num1 + num2
RequestQuantityTxtBx3.Text = num3
' Perform validation to show appropriate message in the messagebox
If num3 > 0 Then
MsgBox("Accepted")
ElseIf num3 = 0 Then
MsgBox("Quantity is 0")
ElseIf num3 < 0 Then
MsgBox("Quantity below 0")
End If
Else
' Display error if the needed input is not numeric
MsgBox("Error")
End If
Hopefully it helps. Thanks.

how to improve excel vba code of many ifs end ifs

Private Sub Worksheet_Change(ByVal Target As Range)
If [C3] > 0 And [B3] > 0 And [B1] > 0 Then
Sheets("E-L1").Visible = True
Else
Sheets("E-L1").Visible = False
End If
If [C4] > 0 And [B4] > 0 And [B1] > 0 Then
Sheets("E-L2").Visible = True
Else
Sheets("E-L2").Visible = False
End If
If [C5] > 0 And [B5] > 0 And [B1] > 0 Then
Sheets("E-L3").Visible = True
Else
Sheets("E-L3").Visible = False
End If
If [C7] > 0 And [B7] > 0 And [B1] > 0 Then
Sheets("M-L1").Visible = True
Else
Sheets("M-L1").Visible = False
End If
If [C8] > 0 And [B8] > 0 And [B1] > 0 Then
Sheets("M-L2").Visible = True
Else
Sheets("M-L2").Visible = False
End If
If [C10] > 0 And [B10] > 0 And [B1] > 0 Then
Sheets("MIDPI-1").Visible = True
Else
Sheets("MIDPI-1").Visible = False
End If
If [C11] > 0 And [B11] > 0 And [B1] > 0 Then
Sheets("MIDPI-2").Visible = True
Else
Sheets("MIDPI-2").Visible = False
End If
If [C13] > 0 And [B13] > 0 And [B1] > 0 Then
Sheets("BR-1").Visible = True
Else
Sheets("BR-1").Visible = False
End If
If [C14] > 0 And [B14] > 0 And [B1] > 0 Then
Sheets("BR-2").Visible = True
Else
Sheets("BR-2").Visible = False
End If
If [C15] > 0 And [B15] > 0 And [B1] > 0 Then
Sheets("BR-3").Visible = True
Else
Sheets("BR-3").Visible = False
End If
If [C16] > 0 And [B16] > 0 And [B1] > 0 Then
Sheets("BR-4").Visible = True
Else
Sheets("BR-4").Visible = False
End If
If [C18] > 0 And [B18] > 0 And [B1] > 0 Then
Sheets("BR-LR1").Visible = True
Else
Sheets("BR-LR1").Visible = False
End If
If [C19] > 0 And [B19] > 0 And [B1] > 0 Then
Sheets("BR-LR2").Visible = True
Else
Sheets("BR-LR2").Visible = False
End If
If [C20] > 0 And [B20] > 0 And [B1] > 0 Then
Sheets("BR-LR3").Visible = True
Else
Sheets("BR-LR3").Visible = False
End If
If [C21] > 0 And [B21] > 0 And [B1] > 0 Then
Sheets("BR-LR4").Visible = True
Else
Sheets("BR-LR4").Visible = False
End If
If [C23] > 0 And [B23] > 0 And [B1] > 0 Then
Sheets("BR-SR1").Visible = True
Else
Sheets("BR-SR1").Visible = False
End If
If [C24] > 0 And [B24] > 0 And [B1] > 0 Then
Sheets("BR-SR2").Visible = True
Else
Sheets("BR-SR2").Visible = False
End If
If [C26] > 0 And [B26] > 0 And [B1] > 0 Then
Sheets("MOD-F1").Visible = True
Else
Sheets("MOD-F1").Visible = False
End If
If [C27] > 0 And [B27] > 0 And [B1] > 0 Then
Sheets("MOD-F2").Visible = True
Else
Sheets("MOD-F2").Visible = False
End If
If [C29] > 0 And [B29] > 0 And [B1] > 0 Then
Sheets("MOD-S1").Visible = True
Else
Sheets("MOD-S1").Visible = False
End If
If [C30] > 0 And [B30] > 0 And [B1] > 0 Then
Sheets("MOD-S2").Visible = True
Else
Sheets("MOD-S2").Visible = False
End If
End Sub
The above checks for 3 criteria for a worksheet to be visible, if all 3 is not satisfied, then worksheet is hidden
i.e. if the 3 criteria is met, then a certain worksheet will be visible
is there a better way of writing the above code?
seems to be redundant
too many ifs and end ifs
Many thanks
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rowsIndex As Variant, sheetNames As Variant
rowsIndex = Array(3,4,5,7,8,10)
sheetNames = Array("E-L1","E-L2","E-L3","M-L1","M-L2","MISPI-1")
Dim index As Long
For index = LBound(rowsIndex) To UBound(rowsIndex)
Sheets(sheetNames(index)).Visible = Cells(rowsIndex(index), 2) > 0 And Cells(rowsIndex(index), 3) > 0 And Cells(1,2) > 0
Next
End Sub
Just fill those two arrays up with all your rows indexes and corresponding sheet names
Anytime you have something like:
If [C3] > 0 And [B3] > 0 And [B1] > 0 Then
Sheets("E-L1").Visible = True
Else
Sheets("E-L1").Visible = False
End If
You can shorten it. Since this :
( [C3] > 0 And [B3] > 0 And [B1] > 0 )
...returns True or False (without an If). ...and if it's True you want Visible=True. Therefore:
Sheets("E-L1").Visible = ( [C3] > 0 And [B3] > 0 And [B1] > 0 )
...is the equivalent. That will make a big change in all the similar sections.
Something that used to seem like a waste of time to me but actually is an important habit is proper spacing and indenting (especially when sharing your code with others of forums!).
There are various Simple example loose rules at ultimately the "style" is up to you, just make sure it's organized whatever it is.
For example, this:
Sub myExample
If [C29] > 0 And [B29] > 0 And [B1] > 0 Then
Sheets("MOD-S1").Visible = True
Else
Sheets("MOD-S1").Visible = False
End If
End Sub
Should be:
Sub myExample
If [C29] > 0 And [B29] > 0 And [B1] > 0 Then
Sheets("MOD-S1").Visible = True
Else
Sheets("MOD-S1").Visible = False
End If
End Sub
One more thing, do not get in the habit of using shorthand like [A1]+[B2]. That form of cell references is full of potential issues, and is mean for us in the immediate window for debugging, not as part of your code.
There are a few "proper" ways you can do it , the most common being, instead of:
[A1]
(declare at least one worksheet at the beginning of the procedure)
Dim ws as Worksheet
Set ws = Worksheets("mySheetName")
...and then you refer to the cell like:
ws.Ramge("A1")
It may seem like a lot more typing but there are important reasons for it. Proper organization will save you (and those you show your code to!) from headaches in the long run.
If you'd like to make that change and update the code in your question, we can take another look.
Slight variation to DisplayName's code which I think is pretty good.
Range B1 was common to all conditions, so why not place that as your first condition, and remove it from the rest of your code. Your ranges came in pairs so add them to an array. I placed all of the first half of the pair in the first half of the array so that you can make use of /2 as a Mod value to get the second half of the array values. The sheets array should of course equal your /2 value
Sub sheetVisibility()
On Error GoTo NoSheet
Dim ranges As Variant, sheets As Variant, arrayLen As Integer
If ([B1] > 0) Then
ranges = Array("C3", "C4", "C5", "C6", _
"B3", "B4", "B5", "B6")
arrayLen = UBound(ranges) / 2
sheets = Array("Sheet1", "Sheet2", "Sheet3", "Sheetx")
For i = 0 To UBound(ranges) Mod arrayLen
sheets(sheets(i)).Visible = (Range(ranges(i)) > 0 And Range(ranges(i + arrayLen)) > 0)
Next i
End If
End
NoSheet:
End Sub

If Else Statement in vb.Net

I wanted to have this condition like i have b2.text, c3.text, d4.text, e5.text, f6.text, g7.text, h8.text, i9.text and j10.text.
And if they are all equal to zero then statement else continue.
i tried
If (b2.Text = 0 & c3.Text = 0 & d4.Text = 0 & e5.Text = 0 & f6.Text = 0 & g7.Text = 0 & h8.Text = 0 & i9.Text = 0 & j10.Text = 0) Then
a1.Text = 10000000
Else
Msgbox.Show("Cannot sort")
End if
Unfortunately i remembered & function only accept two variable only :P
How can i do it?
Thank you
You don't want & for VB, you want AndAlso. And while it is probably a bit above your level, you might want to look into Linq.
If ({b2.Text, c3.Text, d4.Text, e5.Text, f6.Text, g7.Text, h8.Text, i9.Text, j10.Text}).All(Function(f) f = "0") Then
a1.Text = 10000000
Else
Msgbox.Show("Cannot sort")
End IF
As others have said, you should turn on Option Strict, so that your comparison to an int gets flagged. I made the string "0" above, but you could easily modify it to use length if that is what you actually need.
I don't know what language are you using but I'm pretty sure you can compare more than 2 values The solution may be like this.
if (b2.text == 0 && c3.text == 0 && d4.text == 0 && e5.text== 0 && f6.text == 0 && g7.text == 0 && h8.text == 0 && i9.text == 0 && j10.text == 0) {
// when conditions are true
}
else {
// else code here
}

Finding Substring of String VB

1.The Following Program will get two inputs from user i.e A & B
2. Than Find the sub string from B.
3. Finally Print the result.
While my code is
Dim a As String
Dim b As String
a = InputBox("Enter First String", a)
b = InputBox("Enter 2nd String", b)
Dim i As Integer
Dim j As Integer = 0
Dim k As Integer = 0
Dim substr As Integer = 0
For i = 0 To a.Length - 1
If a(i) = b(j) Then
j += 1
If b(j) = 0 Then
MsgBox("second string is substring of first one")
substr = 1
Exit For
End If
End If
Next i
For i = 0 To b.Length - 1
If b(i) = a(k) Then
k += 1
If a(k) = 0 Then
MsgBox(" first string is substring of second string")
substr = 1
Exit For
End If
End If
Next i
If substr = 0 Then
MsgBox("no substring present")
End If
End Sub
While compiling it gives following debugging errors.
Line Col
Error 1 Operator '=' is not defined for types 'Char' and 'Integer'. 17 24
Error 2 Operator '=' is not defined for types 'Char' and 'Integer'. 27 24
It is because of these lines:
If b(j) = 0 Then
If a(k) = 0 Then
As a(k) and b(j) are both of the Char data type (think of the string as an array of characters) but you are trying to compare them to an int (0).
If you are looking for a substring and you're using VB.NET you could try using the IndexOf method, for a very naive example:
If a.IndexOf(b) > -1 Then
MsgBox("b is a substring of a")
ElseIf b.IndexOf(a) > -1 Then
MsgBox("a is a substring of b")
Else
MsgBox("No substring found")
End
If you are using VBA, you could also use InStr but I think with this the string is 1-indexed instead of 0-indexed (as they are in VB.NET) so your check may look something like:
If InStr(a,b) > 0 Then
MsgBox("b is a substring of a")
ElseIf InStr(b,a) > 0 Then
MsgBox("a is a substring of b")
Else
MsgBox("No substring found")
End