GoTo is not defined - in VBA - excel

When I on the step F8 click. then say it Goto is not defined. I try to make a inputbox with a messagebox that me the answer give. And I try also to make code when the values not correct is. See, you where I make a mistake in my VBA code:
Sub TwoNumbersinputbox()
Dim bytAnswer1 As String
Dim bytAntwer2 As String
Dim Range As Byte
Dim strNumber1 As String
Dim strNumber2 As String
[C3] = "Number1"
[C4] = "Number2"
Start1:
strNumber1 = InputBox("Give number one?", "Invoer", 5, 567, 567)
If IsNumeric(strNumber1) Then
MsgBox "This must be Number1", vbCritical, _
"Number1 input"
GoTo strNumber1
Else: [B2] = strNumber1
End If
If Not IsNumeric(strNumber1) Then
MsgBox "there is error.", vbCritical, "Number2 input"
bytAnwer1 = MsgBox("Start Again?", vbYesNo)
If bytAnwer1 = vbYes Then GoTo Start
End If
Start2:
strGetal2 = InputBox("Give Number2?", "Input", 5, 567, 567)
If IsNumeric(strNumber2) Then
MsgBox "This must be Number2 ", vbCritical, _
"Number2 input"
GoTo strNumber2
Else: [B3] = strNumber2
End If
If Not IsNumeric(strGetal2) Then
MsgBox "Is there an error.", vbCritical, "Number2 input"
bytAnswer2 = MsgBox("Start Again?", vbYesNo)
If bytAnswer2 = vbYes Then GoTo Start
End If
End Sub

First thing first - never use GOTO. Only in error handling (On Error statement (VBA)).
Second - if you need to use it, a mark is needed. E.g., if it is GoTo somewhere, then in the code it should be defined like this - somewhere:.
Sub DontUseGoTo()
Dim i As Long
i = 0
somewhere:
i = i + 1
Debug.Print i
If i < 10 Then
GoTo somewhere
End If
End Sub

Related

VBA Input Function shows Run time error, type mismatch

I want to create a input box, and put the input into corresponding cells. But it show type mismatch.
Sub Profit_Projection()
Dim rng As Range
Dim psales As Integer
Dim msg1 As String
psales = InputBox("Please enter the predicted growth of sales next month in decimal form.", "Sales Growth", 1)
If StrPtr(psales) = 0 Then
MsgBox "You clicked Cancel button"
Exit Sub
ElseIf psales = "" Then
MsgBox "You didnt enter input"
Exit Sub
Else
Val (psales)
Range("B5") = psales * 100
If Range("B5").IsNumeric = False Then
msg1 = "The number inputted is is not integer. Please try again in decimal form."
MsgBox msg1, vbOKOnly, "Incorrect Input"
End If
End If
End Sub
Your main problem is that InputBox returns a String (see the official documentation), but you assign it to a numeric variable.
If the user enters some non-numeric data, you will get the type mismatch already at the psales = InputBox - statement.
If the user enters a numeric value, VBA will convert it into a number. But then you get a a type mismatch for the statement psales = "" because you cannot compare a number and a string (even if it is an empty string).
So you should assign the result of the InputBox first to a String variable and then check step by step if the entered value was okay:
Sub Profit_Projection()
Dim rng As Range
Dim psales As Integer
Dim answer
Dim msg1 As String
answer = InputBox("Please enter the predicted growth of sales next month in decimal form.", "Sales Growth", 1)
If StrPtr(answer) = 0 Then
MsgBox "You clicked Cancel button"
Exit Sub
End If
If Trim(answer) = "" Then
MsgBox "You didnt enter anything"
Exit Sub
End If
If Not IsNumeric(answer) Then
MsgBox "You didnt enter a number"
Exit Sub
End If
If CInt(answer) <> Val(answer) Then
MsgBox "You didnt enter an integer "
Exit Sub
End If
psales = Val(answer)
ActiveSheet.Range("B5") = psales * 100
End Sub

How to select a sheet from a user input box

I am having trouble coding this VBA code. I need the code to ask the user if they want data or a graph. If the user selects Yes From there, I need to the code to look at the selected input and see if that input is a valid sheet name. If not, the input box will display again until valid sheet name. If the sheet is valid, then I need the sheet to be selected or show up whenever the user enters a valid value. I hope that makes sense.
For example, if the user enters (10-1) that is a valid sheet or (1-1) valid sheet but if it is (14-1) or (a-a) that is not a valid sheet.
Note I have not gotten to the graphing part yet, so do not worry about if the user selects no yet. Can someone get me in the correct direction?
Sub InputValidation()
Dim str As String
Dim inp As String
Dim ws As Worksheet
str = MsgBox("Do you want to select a dataset (Yes) or a Graph (No)", vbQuestion + vbYesNo)
If str = vbYes Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
If MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion) = vbYes Then MsgBox "Thank You Goodbye"
Exit Sub
End If
ElseIf inp = "#-#" Or "##-#" Then
If Sheets(ws).Name = inp Then
Worksheets(inp).Activate
End If
Else
MsgBox "This load and test cannot be found"
If str = vbNo Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
If MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion) = vbYes Then MsgBox "Thank You Goodbye"
Exit Sub
End If
End If
End If
End Sub
Please make sure you close all you if statements when using indentation?
The way you have now set it implies that the last End if is covering the entire str = vbYes scope, i.e. if str = vbNo nothing happens?
Sub InputValidation()
Dim str As String
Dim inp As String
Dim ws As Worksheet
str = MsgBox("Do you want to select a dataset (Yes) or a Graph (No)", vbQuestion + vbYesNo)
If str = vbYes Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
If MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion) = vbYes Then MsgBox "Thank You Goodbye"
Exit Sub
'End If
ElseIf inp = "#-#" Or "##-#" Then
If Sheets(ws).Name = inp Then
Worksheets(inp).Activate
End If
Else
MsgBox "This load and test cannot be found"
End If '=> added this End If as it will otherwise skip to end of sequence
ElseIf str = vbNo Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
If MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion) = vbYes Then MsgBox "Thank You Goodbye"
Exit Sub
End If
End If
End Sub
I also think your below line is incorrect?
ElseIf inp = "#-#" Or "##-#" Then
It will give a Type Mismatch error? (Error 13)
You could contemplate using a regex for this assessment or simply use something like the below?
ElseIf inp like "*-*" Then
Which would also do the trick?
The subsequent statement tries to select the Worksheet but that won't work as you have not set the ws object anywhere? So the below line is incorrect in many ways:
If Sheets(ws).Name = inp Then
Please see below code that will give you a good base to start from?
This would also get rid of the unnecessary inp = "#-#" comparison
Private Function SheetExists(name As String) As Boolean
SheetExists = False
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.name = name Then SheetExists = True: Exit Function
Next
End Function
Private Function ConfirmEndSub()
ConfirmEndSub = MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion)
If ConfirmEndSub = vbYes Then
MsgBox "Thank You Goodbye"
End If
End Function
Sub InputValidation()
Dim str As String
Dim inp As String
Dim ws As Worksheet
str = MsgBox("Do you want to select a dataset (Yes) or a Graph (No)", vbQuestion + vbYesNo)
If str = vbYes Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
Reply = ConfirmEndSub
If Reply = vbYes Then Exit Sub
ElseIf SheetExists(inp) Then
Worksheets(inp).Activate
Else
MsgBox "This load and test cannot be found"
End If
ElseIf str = vbNo Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
Reply = ConfirmEndSub
If Reply = vbYes Then Exit Sub
End If
End If
End Sub
This leaves entirely out of consideration that depsite the initial vbYesNo answer the user will always get the input box? Not sure if that is the intention, but alas that is how it was written.
One other consideration is that if the user selects not to Quit, the call is not returning to the request for input? => I.e. it is still ending the routine...

Find & Delete subroutine are not working in Excel

User enters the Waypoint id and then press delete record it, so data of that particular waypoint id should be delete from observations table.
Written a subroutine where my vba code first find the waypoint id in the observation worksheet, get the row number and then delete the row number and move the cell up. If it doesnot find the waypoint id then message should appear Waypoint id not found and cannot be deleted.
My vba code is not working. Can anyone help me to fix this issue? Attach File with name Problem.xlsm
Sub FindRecord(WyPt)
Dim Value As String
WyPtRow = 0
ReadRow = 2
Value = Cells(ReadRow, 2).Select 'Observation Sheet-WayPointID
While Value <> ""
If WyPt = Value Then
WyPtRow = ReadRow
Exit Sub
End If
ReadRow = ReadRow + 1
Value = Cells(ReadRow, 2)
Wend
End Sub
Sub DeleteRecord()
Set DEFrm = Sheets("DataEntryForm")
Set ObsData = Sheets("Observations")
WyPt = Trim(DEFrm.Cells(6, 2)) 'DataEntryForm worksheet-WayPointID
Call FindRecord(WyPt)
If WyPtRow > 0 Then
Worksheets("Observations").Rows(WyPtRow).Delete Shift:=xlShiftUp
MsgBox "WaypointID found", vbOKOnly + vbCritical, "Deleted Succesfully"
End If
If WyPtRow = 0 Then
MsgBox "WaypointID Not found", vbOKOnly + vbCritical, "We can't delete the record"
Exit Sub
End If
End Sub
I suggest you use application.match to find the row to delete.
I have not downloaded your file so this may need to adjustments.
Sub FindRecord()
Set DEFrm = Sheets("DataEntryForm")
WyPt = Trim(DEFrm.Cells(6, 2).value)
WyPtRow = application.match(WyPt, range("B:B"),0)
if not iserror(WyPtRow) then
DeleteRecord(WyPtRow)
else
msgbox "No waypoint found"
end if
End sub
Sub DeleteRecord(WyPtRow)
Worksheets("Observations").Rows(WyPtRow).EntireRow.Delete
End sub
Edit sorry I see now that I made the code in reverse.
My idea was to call FindRecord and it calls delete, I see now that you called Delete and it called find.
Try this code.
Sub DelRow(WyPt As String)
Dim i As Long
For i = 2 To 65536
If Cells(i, 2).Text = WyPt Then
Worksheets("Observations").Rows(i).Delete Shift:=xlShiftUp
MsgBox "WaypointID found", vbOKOnly + vbCritical, "Deleted Succesfully"
Exit Sub
End If
If Cells(i, 2).Text = "" Then 'stop on first empty row
Exit For
End If
Next
MsgBox "WaypointID Not found", vbOKOnly + vbCritical, "We can't delete the record"
End Sub

application.inputbox error after clicking OK with empty input

I really searched hours and hours, but I can't find any solutions.
You should only enter numbers into the Inputbox and a msgbox should sppears when you just hit ok without any number or string...
The first part was easy, but I always get an error message by just hitting OK!
Public Sub test()
Dim vntReturn As Variant
vntReturn = Application.InputBox("Bitte Wert eingeben", "Eingabe", , , , , , 1)
If StrPtr(vntReturn) = 0 Then
MsgBox "Abbrechen gedrückt"
Else
If vntReturn = False Then
MsgBox "Nix eingegeben"
Else
MsgBox vntReturn
End If
End If
End Sub
This is happening because you're declaring the Type for this InputBox to a number. So excel will automatically try to correct this. You can use an InputBox without a Type and program your own verification for checking if it's an integer or not.
Otherwise you can also add this before your code:
Application.DisplayAlerts = False
And then set it to True after. Now when you hit ok you won't be prompted with the error, but the InputBox will not go away. You could add additional instructions to the InputBox to make it clear it needs a number.
#mehow: as Alex D just said: Your answers are similar ;-)
First I used the code of mehow, but now I just create a userform with only an "OK-button".
Private Sub Rechnen_Click()
Dim i As Integer ' Variable deklarieren
Dim Sum As Integer
Dim counter As Variant
i = 0 ' deklariert, löst beim Kompilieren keinen Fehler aus
Sum = 0 ' nicht deklarierte Variable löst beim Kompilieren einen Fehler aus
counter = TextBox1.Value
Application.DisplayAlerts = False
If Not IsNumeric(counter) Then
Exit Sub
Else
Unload Userform1
On Error Resume Next
Do Until i >= counter
Zahl = InputBox("Pls enter a number:", i + 1 & ". Versuch")
Sum = Sum + Zahl
i = i + 1
If Not IsNumeric(Zahl) Then
MsgBox "calculation premature cancelled!"
Exit Do
End If
Loop
Ausgabe = MsgBox("Die Summe lautet: " & Sum, vbInformation, "Ergebnis")
Question = MsgBox("is it enough?", vbYesNo + vbQuestion, "repeat")
If Question = vbNo Then
Userform1.Show
Else
Unload Userform1
Exit Sub
End If
End If
End Sub
and so the userform looks like:
Now the program works fine ;) Thank you guys!

Input Box Error Handling

I am having trouble handling the error associated with a input box "Cancel" click. Or in otherwords, it returns an error within the sub if the value of the input is null. I have tried looking around and still can't seem to get it quite right. Here is my attempt:
Private Sub bttnSavingsExpected_Click()
Dim expected() As String
Dim nPeriods As Integer
Dim counter As Integer
Dim savings As Single
With ActiveSheet.Range("A13")
nPeriods = Range(.Offset(1, 0), .End(xlDown)).Rows.Count
End With
ReDim expected(1 To nPeriods)
counter = 1
For counter = 1 To nPeriods
expected(counter) = Range("A13").Offset(counter, 0).Value
Next
TryAgain:
On Error GoTo ErrH
counter = 1
For counter = 1 To nPeriods
savings = InputBox("How much savings do you expect from " & expected(counter) & "?", "Savings?", Range("A13").Offset(counter, 1).Value)
If savings = "" Then
Exit Sub
Else
Range("A13").Offset(counter, 1).Value = savings
End If
Next
Exit Sub
ErrH:
MsgBox "Please enter value. If the default value is desired then please click 'OK'.", vbOKOnly, "Do Not Click Cancel"
GoTo TryAgain
End Sub
With this attempt, the MsgBox is displayed the first click whether there is a input or not and even if I click "Ok". The second try of clicking "OK" or "Cancel" leads to being kicked back to the editor.
You've got Dim savings As Single and If savings = "" Then. Thats always going to error
Try using Dim savings As Variant
Make sure the variable for the Inbox is set at "", then test the value for False. Much easier than anything else I have seen:
Sub WolfPackURL_input()
Dim TheURL As String
Dim SaveURL As Hyperlink
Set savedURL = Sheets("Data").Range("I1")
TheURL = ""
TheURL = Application.InputBox("Input the Sign-Up URL", "Wolfpack Weekly Players URL", "http://something", 1)
If TheURL = "False" Then
Exit Sub
End If
ThisWorkbook.Worksheets("Data").Activate
Sheets("Data").Range("I1").Hyperlinks.Delete
Sheets("Data").Range("I1").ClearContents
Sheets("Data").Range("I1").Clear
ActiveSheet.Hyperlinks.Add anchor:=Sheets("Data").Range("I1"), Address:=TheURL, ScreenTip:="Open file", TextToDisplay:=TheURL
End Sub

Resources