Looping back to input box after error occurs - vba

Just doing a quick exercise below, an input box that converts inches to cm's.
I want to add to the error handler section so that after the msgbox appears explaining an error has occurred it loops back to the inputbox asking me to add inches to convert to centimeters. Thanks
Sub Exercise()
Dim m As Variant
Dim result
Dim ErrM As String
On Error GoTo ErrHandler
m = InputBox("How much in Inches would you like to convert to Centimeters?", "Inches to Centimeters", "Please Type here")
result = m * 2.54
MsgBox "There are " & result & " inches", , "Result"
Exit Sub
ErrHandler:
MsgBox ("An error occured, please type a number into the input box")
End Sub

There's no need for error handling in your specific case. Simply, throw the InputBox in a loop, check if the input is a number (e.g., using IsNumeric), and decide whether you should continue or repeat based on that.
Example:
Do While True
m = InputBox("How much in Inches would you like to convert to Centimeters?", _
"Inches to Centimeters", "Please Type here")
If StrPtr(m) = 0 Then
' The user canceled the operation.
Exit Sub
ElseIf Not IsNumeric(m) Then
' The input is not a number.
MsgBox ("Please type a number into the input box.")
Else
' The input is a number. We continue with the code below.
Exit Do
End If
Loop
result = m * 2.54
MsgBox "There are " & result & " inches", , "Result"

Try this way, please:
Sub Exercise()
Dim m As Variant, result As Double
BackInp:
m = InputBox("How much in Inches would you like to convert to Centimeters?", "Inches to Centimeters", "Please Type here")
If Not IsNumeric(m) Then
MsgBox "An error occurred, please type a numeric value into the input box!", _
vbInformation, "Need to repeate the input..."
GoTo BackInp
End If
result = m * 2.54
MsgBox "There are " & result & " inches", , "Result"
End Sub

Related

MS Access VBA - Loop Split Function and Output Either First Value (If Not Null) or Last Value

I have a field in my Access database that contains values such as 24,25,152, 128,152, ,113, 113 and NULLS.
When there is only one value present in the field I would like the first value to be my output (113 for ,113 and 113) and when there is more than one value present I would like the last value to be my output (152 for 24,25,152 and 128,152).
Right now I have a user-defined function that is invoked by a query that has been hard-coded to account for the correct number of commas/values present in the field. In the future there will be more commas so I would like to account for those and I'd like my output to be in a single column (as opposed to having one column per value after each comma).
Here is VBA code for that user-defined function which came from this post.
Function mySplit(sMyText As String, sDelim As String, lIndx As Long) As String
On Error GoTo Error_Handler
mySplit = Split(sMyText, sDelim)(lIndx)
Error_Handler_Exit:
On Error Resume Next
Exit Function
Error_Handler:
If Err.Number = 9 Then
mySplit = ""
Else
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: mySplit" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
End If
Resume Error_Handler_Exit
End Function
Here is the query:
SELECT Field, mySplit([field].[table],",",0) AS 1, mySplit([field].[table],",",1) AS 2, mySplit([field].[table],",",2) AS 3, Val(IIf([3]<>"",[3],IIf([2]<>"",[2],IIf([1]<>"",[1])))) AS [Value]
FROM Table;
Ideally I'd to have a single field that looks like the "Value" field (outlined in green) in the image below.
Right now that value field is a bunch of nested if statements looking at the 1, 2, and 3 columns. I know I need to modify this code to count the delimiters and then loop through each delimiter and take either the first value (if there is only one) and the last value (if there is more than one) but I am not sure how to go about achieving that.
Any help will be greatly appreciated.
EDIT
Try this.
Just Split the value and return the last element in the array. If the value is null, return an empty string.
Public Function SplitToLast(Value As Variant) As String
On Error GoTo Trap
If IsNull(Value) Then GoTo Leave
Dim arr As Variant
arr = Split(Value, ",")
SplitToLast = arr(UBound(arr))
Leave:
On Error GoTo 0
Exit Function
Trap:
MsgBox Err.Description, vbCritical
Resume Leave
End Function
Try this:
Public Function GetLastValue(ByVal value As Variant, ByVal delimiter As String) As String
If IsNull(value) Then Exit Function
If Len(delimiter) = 0 Then
GetLastValue = value
Exit Function
End If
Dim tmpValue As String
tmpValue = Trim(CStr(value))
Do While tmpValue Like "*" & delimiter
tmpValue = Trim(Left(tmpValue, Len(tmpValue) - Len(delimiter)))
Loop
If Len(tmpValue) = 0 Then Exit Function
Dim tmpArr() As String
tmpArr = Split(tmpValue, delimiter)
GetLastValue = tmpArr(UBound(tmpArr))
End Function
It also takes care of multiple delimiters at the end of the value like 1,2,3,, ,.
It also works if the length of the delimiter is > 1.
In case value is an empty string, the result will be an empty string too.
In case delimiter is an empty string, the result will be value.
This example calling works fine:
SELECT GetLastValue([Field1],",") AS LastValue FROM Table1
If you edit the query in the query design view and not in SQL view, take care of the , which separates the parameters. There it must be a ; instead.

Visual Basic, number range in IF statements

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

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.

Getting Error No.: 424 object required upon using String.Length in VBA

I am want to get length of a string. But I am getting error Error No.: 424 object required .
Dim Start as String
Dim LengthofStart as Integer
If Start <> "" Then
MsgBox ("Going to calculate length now::")
lengthofstart = Start.Length
MsgBox ("The lenght of start is " & LengthofStart)
End If
The error is appearing when I get the length of string "Start".
Try Len(Start) instead
lengthofstart = Len(Start)

Unexpected String Results

I have the following code to check values entered into two input boxes, if both values are zero then the MsgBox should display "Stop!" (I will change this later to exiting the sub but I am using a MsgBox for testing)
From testing I've seen these results:
A zero in both strings produces the expected message box.
A non zero in the first string followed by any non zero value in the second string does nothing (as expected).
A zero in the first string followed by a second string value equal to or greater than 10 produces the message box (unexpected).
I've also noticed that if the second string is 6-9 it is displayed as x.00000000000001%. I think this is a floating point issue and could be related? This behaviour occurs without the IF... InStr function too.
Option Explicit
Sub Models()
Dim MinPer As String, MaxPer As String, Frmula As String
Dim Data As Worksheet, Results As Worksheet
Set Data = Sheets("Data")
Set Results = Sheets("Results")
Application.ScreenUpdating = False
MinPer = 1 - InputBox("Enter Minimum Threshold Percentage, do not include the % symbol", _
"Minimum?") / 100
MaxPer = 1 + InputBox("Enter Maximum Threshold Percentage, do not include the % symbol", _
"Maximum?") / 100
If (InStr(MinPer, "0") = 0) And (InStr(MaxPer, "0") = 0) Then
MsgBox "STOP!"
End If
' Remainder of code...
This is the most interesting problem I've come across so far in VBA and welcome any discussion about it.
Edit: I use this code to display on screen the paramaters for the end-user to see. Hence how I noticed the .00000000001% issue:
.Range("D2").Value = "Min is " & 100 - MinPer * 100 & "%"
.Range("D3").Value = "Max is " & MaxPer * 100 - 100 & "%"
Two things
1) Declare MinPer, MaxPer as Long or a Double and not a String as you are storing outputs from a calculation
2) Don't directly use the InputBox in the calculations. Store them in a variable and then if the input is valid then use them in the calculation
Dim MinPer As Double, MaxPer As Double, Frmula As String
Dim Data As Worksheet, Results As Worksheet
Dim n1 As Long, n2 As Long
Set Data = Sheets("Data")
Set Results = Sheets("Results")
Application.ScreenUpdating = False
On Error Resume Next
n1 = Application.InputBox(Prompt:="Enter Minimum Threshold Percentage, do not include the % symbol", _
Title:="Minimum?", Type:=1)
On Error GoTo 0
If n1 = False Then
MsgBox "User cancelled"
Exit Sub
End If
On Error Resume Next
n2 = Application.InputBox(Prompt:="Enter Maximum Threshold Percentage, do not include the % symbol", _
Title:="Maximum?", Type:=1)
On Error GoTo 0
If n2 = False Then
MsgBox "User cancelled"
Exit Sub
End If
If n1 = 0 And n2 = 0 Then
MsgBox "STOP!"
End If
MinPer = 1 - (Val(n1) / 100)
MaxPer = 1 + (Val(n2) / 100)
This is because the number "10" has a "0" in the string (second character) so both evaluate to true.
Try this instead:
If (MinPer = "0") And (MaxPer = "0") Then
MsgBox "STOP!"
End If
For additional control save the user input (MinPer , MaxPer) and THEN text them for validity before performing nay mathematical operations on them.
InStr(MinPer, "0") is just checking to see whether the string contains a zero
character.
You need to convert the string value to an integer. Use the IsNumeric and CInt functions
to do that. See this URL:
vba convert string to int if string is a number
Dim minPerINT as Integer
Dim maxPerINT as Integer
If IsNumeric(minPer) Then
minPerINT = CInt(minPer)
Else
minPerINT = 0
End If
If IsNumeric(maxPer) Then
maxPerINT = CInt(maxPer)
Else
maxPerINT = 0
End If
If minPerINT = 0 and maxPerINT=0 Then
MsgBox "STOP!"
End If
Depending on what data can be entered It may also be a good idea to check if the length
of the data is zero using the len() function.