Visual Basic, number range in IF statements - vba

how would i write this line of c# in visual basic. im trying to get a input from the user and provide a result, given the input falls between a number range.
if int(>65 || <=73)
{
}
This is the code i have so far.
Dim Hb As String = txtInput1.Text
If IsNumeric(Hb) Then
Dim HbInt As Integer = Integer.Parse(Hb)
Else
Output("The Hb value needs to be numeric")
End If

For Reference See this.
This Dim Hb As String = txtInput1.Text is not allowed in vba and I assume txtInput1 is a named reference to a cell range.
You have to write it as below
Dim Hb As String: Hb = txtInput1.Text
Also this Dim HbInt As Integer = Integer.Parse(Hb) isn't right as well
The right way would be:
Dim HbInt As Integer: HbInt = CInt(Hb)
So the code for your need would be:
Sub NumRange()
Dim Hb As String: Hb = txtInput1.Text
if IsNumeric(Hb) then
Dim HbInt As Integer: HbInt = CInt(Hb)
if HbInt > 65 And HbInt <=73 then
Do things......
Else
Msgbox "Number Entered is out of Range"
End if
Else
Msgbox "Invalid Input."
End if
End Sub

Just expanding upon the answer provided by #NewGuy I'd rather use the Select Case statement to evaluate the number provided. This will allow for more options:
Option Explicit
Sub tmpTest()
Dim strHB As String
strHB = InputBox("Give me a number between 1 and 100", "Your choice...")
If IsNumeric(strHB) Then
Select Case CLng(strHB)
Case 66 To 73
MsgBox "You picked my range!"
Case 1 To 9
MsgBox "One digit only? Really?"
Case 99
MsgBox "Almost..."
Case Else
MsgBox "You selected the number " & strHB
End Select
Else
MsgBox "I need a number and not this:" & Chr(10) & Chr(10) & " " & strHB & Chr(10) & Chr(10) & "Aborting!"
End If
End Sub

Like this:
If HbInt > 65 And HbInt <= 73 Then
...
End If

Related

Cant get my loop to work if there are more then one condition vba

I am trying to right a macro that allows a user to input either 1, 2 or 3 and that come back with a message telling the user what number they picked. If the user puts in anything other then 1, 2 or 3 I want an error message to pop up, and then the user to be asked again to enter 1, 2 or 3. The problem I am having is that I can't get the loop to work if I put anything more then 1 condition in it. Here is my code
Public Sub ForecastReport()
Dim sinput As Integer
Do
sinput = Application.InputBox("Please select 1 to 3 " & vbLf & vbLf & "1. GB IMCP" & vbLf & "2. IE IMCP" & vbLf & "3. US", "Enter a Value")
Select Case sinput
Case 1
MsgBox ("you have selected GB IMCP")
Case 2
MsgBox ("you have selected IE IMCP")
Case 3
MsgBox ("you have selected US")
Case Else
MsgBox ("wrong input")
End Select
Loop Until sinput <> 3
End Sub
Thank You
For simplicity's sake I often just use a boolean toggle to handle when such a loop should be exited. This also handles the case where the inputbox returns a false, because the user has clicked cancel. Below you can see how I've done this for an inputbox where I want the value it returns to be a year between 2000 and 2050 (år = year). Usine InputBox type:=1 makes the inputbox only accept integers, which will be useful in your case as well.
Dim år As Variant
Dim gyldigVerdi As Boolean
Do
år = Application.InputBox(Prompt:="Question", Title:="Title", Default:=Year(Date) + 1, Type:=1)
If Not CBool(år) Then
Exit Sub
ElseIf CLng(år) < 2000 Or CLng(år) > 2050 Then
MsgBox Prompt:="Error-message", Buttons:=vbExclamation, Title:="Title"
gyldigVerdi = False
Else
gyldigVerdi = True
End If
Loop Until gyldigVerdi
Note that I use Application.InputBox instead of the generic VBA InputBox - for some of the differences between the two, you can have a look at this page.
If you're just interested in the comparison which will return true if the value is between one and three, have a look at the conditions for the first ElseIf, and use the opposite (x >= 1 And x <= 3).
Try like this:
Loop Until sinput <= 3 And sinput > 0
It should be enough.

Using VLOOKUP to search different sheets

I am trying to search if a number exists in one of the 32 sheets I have in my workbook.
I have tried to use the below mentioned code but it's not working because VLOOKUP is not deciphering the variable(n). Kindly help:
Private Sub SearchAll_Click()
Dim SearchCriteria As Double, s As Integer
SearchCriteria = Me.SearchBox.Value
s = 0
For s = 0 To ThisWorkbook.Sheets.Count
s = s + 1
If Application.WorksheetFunction.VLookup(SearchCriteria, Sheets(s).Range("A:A").Value, 1, False) = SearchCriteria Then
MsgBox ("The Number " & SearchCriteria & " is available in list " & Sheets(s).Name)
Exit For
Else
MsgBox ("The Number is Unavailable")
End If
Next s
End Sub
Legend:
SearchAll is a button used to initiate the search.
SearchCriteria is a textbox used to input the value you want to search for.
There are a few problems in the way you use Application.WorksheetFunction.VLookup to determine if a specific value exists in your workbook. I have modified your code to the following:
Private Sub SearchAll_Click()
Dim SearchCriteria As Double, s As Integer
Dim Lookup As Variant
Dim Match As Boolean
SearchCriteria = Me.SearchBox.Value
For s = 1 To ThisWorkbook.Sheets.Count
Lookup = Application.VLookup(SearchCriteria, Sheets(s).Range("A:A"), 1, False)
If Not IsError(Lookup) Then
MsgBox ("The Number " & SearchCriteria & " is available in list " & Sheets(s).Name)
Match = True
Exit For
End If
Next s
If Match = False Then MsgBox ("The Number is Unavailable")
End Sub
Here I have, instead, made use of Application.VLookup which will return an error to the variant variable Lookup if the search value were not found in the specific sheet. Then, by looking at the error state of Lookup it can be determined if the search value were found. Also, I have moved the message The Number is Unavailable outside the loop in order to avoid it being triggered each time the value were not found in a specific sheet.

How to Count the Number of a Specific Character in a Cell with Excel VBA

I have a number of items in cells that are separated by dashes. I'm trying to normalize the database by splitting rows so that each row contains only one entry. How do you find/count strings in Excel VBA. I know you can do values for whole cells with
myVar = Application.WorksheetFunction.COUNTIF(Range("A1:Z100"),"Value")
I need to search a single cell and find out how many hyphens there are. Example
123-456-789 = 2
9876-12 = 1
Using hint from ron's function above I've created this formula and it worked fine :
=LEN(A1) - LEN(SUBSTITUTE(A1, "-", ""))
This will count the number of hyphens in the activecell
Sub test()
a = Len(ActiveCell)
my_txt = Replace(ActiveCell, "-", "", 1, -1, vbTextCompare)
b = Len(my_txt)
numb_occur = a - b
End Sub
Here's the UDF to count single string occurence in string:
Option Explicit
Function COUNTTEXT(ref_value As Range, ref_string As String) As Long
Dim i As Integer, count As Integer
count = 0
If Len(ref_string) <> 1 Then COUNTTEXT = CVErr(xlErrValue): Exit Function
For i = 1 To Len(ref_value.value)
If Mid(ref_value, i, 1) = ref_string Then count = count + 1
Next
COUNTTEXT = count
End Function
Here's using Array formula:
=SUM(IF(ISERROR(SEARCH("-",MID(A1,ROW(INDIRECT("$1:$" & LEN(A1))),1))),0,1))
Entered using Ctrl+Shift+Enter.
Hope this helps.
I found this answer:
Sub xcountCHARtestb()
'If countCHAR(RANGE("aq528"), ".") > 0 Then 'YES
If countCHAR(Selection, ".") > 0 Then 'YES
MsgBox "YES" & Space(10), vbQuestion ', "title"
Else
MsgBox "NO" & Space(10), vbQuestion ', "title"
End If
End Sub
Sub xcountCHARtesta() 'YES
MsgBox "There are " & countCHAR(Selection, "test") & " repetitions of the character string", vbQuestion 'YES
End Sub
Function countCHAR(myString As String, myCHAR As String) As Integer 'as: If countCHAR(Selection, ".") > 1 Then selection OR RANGE("aq528") '"any char string"
countCHAR = UBound(split(myString, myCHAR)) 'YES
End Function
This code might be of your help .. you can also use it as a UDF... :)
Function CountHypens(rng_Src As Range) As Long
'A VARIANT FOR SPLITTING CELL CONTENTS
Dim var As Variant
On Error Resume Next
var = Split(rng_Src.Value, "-", , vbTextCompare)
If Err.Number <> 0 Then
Debug.Print "This cell does not have any hyphens."
Else
CountHypens = UBound(var)
End If
Err.Clear: On Error GoTo 0
End Function
Follow up to: davex, by davex.. :)
I had been looking all over trying to find a way to test same for find text string in a formula.
This answer seems to work correctly for both formulas / not & fits in a 1 liner..
(am still pretty novice at vba, let me know if any better way(s) ) thanks.
If countChar(UCase(Selection.Formula), UCase("offset")) > 0 Then 'YES (thee? answer, works for both formulas / not)
'If countChar(Selection.Formula, "OFFSET") > 0 Then 'yes
'If countChar(Cells(ActiveCell.row, Selection.Column).Formula, "OFFSET") > 0 Then 'yes
'If countChar(Cells(ActiveCell.row, "BG").Formula, "OFFSET") > 0 Then 'yes
'If countChar(UCase(Selection), UCase("OffSET")) > 0 Then 'yes but not work on formula
'If Selection.Formula Like "*offset*" Then 'no (for eq)
MsgBox "YES" & Space(15), vbQuestion
Else
MsgBox "NO" & Space(15), vbQuestion
End If
NOTE: in place of variable "BG" above, i use permanent work cells to improve use for column BG example, work cell A3 has / shows: BG:BG
=SUBSTITUTE(SUBSTITUTE(CELL("address",$BG3),"$",""),ROW(),"")&":"&SUBSTITUTE(SUBSTITUTE(CELL("address",$BG3),"$",""),ROW(),"")
you will also need to dim the work cell, at the top / before the vba:
Dim A3 As String
A3 = RANGE("A3")
pardon, tried 3 times to get all of code into 1 box. really suggest putting a code stop start icon in the toolbar.

If a listbox contains an item LIKE

Is there anywhere to check whether a listbox contains an item which is similar to a string?
I have tried to use a Like statement but this doesn't work.
I have tried:
For i As Integer = 0 To TopicListBox.Items.Count - 1
If (TopicListBox.Items(i).ToString.Contains(Record.Item("Keyphrase2"))) Then
Dim Item As String = TopicListBox.Items(i).ToString
If Item Like "Questions related to:" & Record.Item("Keyphrase2") & ": |*| Qs" Then
Dim ItemSplit() As String = Item.Split(New Char() {"|"c})
Dim AmountOfQuestionsAfter As Integer = AmountOfQuestions + CInt(ItemSplit(1))
Item = ItemSplit(0) & AmountOfQuestionsAfter & ItemSplit(1)
Else
TopicListBox.Items.Add("Questions related to:" & Record.Item("Keyphrase2") & ": |" & AmountOfQuestions & "| Qs")
Exit For
End If
End If
Next
I don't really understand what you are trying to accomplish, but here is a LINQ function to return all the items that contain a certain string.
Dim lb As New ListBox
lb.Items.Add("asdf")
lb.Items.Add("asdfasdf")
lb.Items.Add("aifisasdf")
lb.Items.Add("adf")
'' find all items in the ListBox that contain the string "asdf"
Dim found = lb.Items.Cast(Of String).Where(Function(f) f.Contains("asdf"))
For Each s In found
'' do something with those items
Next
Can't you just do
If Item.Contains("Questions related to:" & Record.Item("Keyphrase2")) Then
...
End If
or
If Item.StartsWith("Questions related to:" & Record.Item("Keyphrase2")) Then
...
End If
?
Dim Found = (From Result In lb.Items Where Result.ToString = "Value" Select Result)
If (Found.Count > 0) Then
' your code
End If

Check if a string variable has an integer value

I am working on a project which allows kids to send a message to Santa. Unfortunately, if they enter a string instead of an integer in the AGE field, the program crashes and returns Conversion from string "[exampleString]" to type 'Double' is not valid.
Is there any way to check if they have entered an integer or not? This is the code.
If childAge > 0 And childAge < 150 Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
Thanks,
Kai :)
A very simple trick is to try parse the string as an Integer. If it succeeds, it is an integer (surprise surprise).
Dim childAgeAsInt As Integer
If Integer.TryParse(childAge, childAgeAsInt) Then
' childAge successfully parsed as Integer
Else
' childAge is not an Integer
End If
Complementing Styxxy's response, if you dont need a result just replace it by vbNull:
If Integer.TryParse(childAge, vbNull) Then
You could perform the following two tests to be reasonably certain that the input you're getting is an integer:
If IsNumeric(childAge) AndAlso (InStr(1, childAge, ".") <> 0) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
If childAge < 0 OrElse childAge > 150 Then
fmSecA2 = "I don't believe it's possible to be" & childAge & " years old..."
End If
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
The InStr function returns zero if it doesn't find the string that is being looked for, and so when combining that test with IsNumeric, you also rule out the possibility that some floating point data type was entered.
IsNumeric is built into VB, and will return a true/false
If IsNumeric(childAge) AndAlso (childAge > 0 And childAge < 150) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
You can use this.
Sub checkInt()
If IsNumeric(Range("A1")) And Not IsEmpty(Range("A1")) Then
If Round(Range("A1"), 0) / 1 = Range("A1") Then
MsgBox "Integer: " & Range("A1")
Else
MsgBox "Not Integer: " & Range("A1")
End If
Else
MsgBox "Not numeric or empty"
End If
End Sub
Working from Styxxy's answer, if you parse as a byte rather than an integer, then it also checks negative ages and maximum age of 255 all in one go.
Dim childAgeAsByte As Byte
If Byte.TryParse(childAge, childAgeAsByte) Then
' childAge successfully parsed as Byte
Else
' childAge is not a Byte
End If
Kristian
Dim Input
Input = TextBox1.Text
If Input > 0 Then
............................
............................
Else
TextBox2.Text = "Please only enter positive integers"
End If
Try
If TextBox1.Text > 0 Then
Label1.Text = "Integer"
End If
Catch ex As Exception
Label1.Text = "String"
End Try
With this you can put anything in TextBox1, if you put text then you get Label1 is string and if you put number then you get it's integer
In .Net you may use GetType() to determine the data type of a variable.
Dim n1 As Integer = 12
Dim n2 As Integer = 82
Dim n3 As Long = 12
Console.WriteLine("n1 and n2 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n2.GetType()))
Console.WriteLine("n1 and n3 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n3.GetType()))
' The example displays the following output:
' n1 and n2 are the same type: True
' n1 and n3 are the same type: False
Based on the above sample you can write a code snippet:
If childAge.GetType() = "Integer" then '-- also use childAge.GetType().Name = "Int32"
' do something
End if
Reference MSDN