VB.net validating textbox input for integers crash - vb.net

I have a form in where users need to input integers to save to an xml when they press a button
the issue lies that when the user does not put in valid input, it displays the error but still attempts to declare the variables for my function and then crashes - how do i stop this?
here's my code:
If IsNumeric(txtLevel.Text) And IsNumeric(txtHealth.Text) Then
MsgBox("choose a location to save in")
ElseIf String.IsNullOrWhiteSpace(txtHealth.Text) Or String.IsNullOrWhiteSpace(txtLevel.Text) Then
MsgBox("you have not filled in all fields")
Me.Close()
Else MsgBox("please input number form")
End If
Dim strName As String = txtCharacter.Text
Dim intLevel As Integer = txtLevel.Text
Dim intHealth As Integer = txtHealth.Text
Dim strStat As String = cmbStat.Text

You are using quite a few legacy features and you also have Option Strict turned off.
IsNumeric should be replaced with Integer.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse
MsgBox should be replaced with MessageBox: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.messagebox
For more information on option strict, I suggest you check out any of these resources:
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/option-strict-statement
https://www.vblessons.com/lessons.html#/1/2
http://vb.net-informations.com/language/vb.net_option_strict.htm
With that being said, your code could look like this:
Dim strName As String = txtCharacter.Text
Dim strStat As String = cmbStat.Text
Dim intLevel, intHealth As Integer
' if either condition is true, close the form prematurely
If (String.IsNullOrWhitespace(txtLevel.Text) OrElse String.IsNullOrWhitespace(txtHealth.Text)) Then
MessageBox.Show("You have not filled in all fields.", "Invalid Form")
Me.Close()
ElseIf (Not Integer.TryParse(txtLevel.Text, intLevel) OrElse Not Integer.TryParse(txtHealth.Text, intHealth)) Then
MessageBox.Show("Please input number form.", "Invalid Form")
Me.Close()
End If
' continue on with the code

Move your variable declaration inside your "If IsNumeric(txtLevel.Text) And IsNumeric(txtHealth.Text) Then" so its only going to try to assign them the value if both txtLevel and txtHealth are integers.
I would suggest you to change the code like so:
'Checks if the textboxes are not empty
If Not String.IsNullOrWhiteSpace(txtHealth.Text) Or String.IsNullOrWhiteSpace(txtLevel.Text) Then
'They are not empty, so the program checks if they are integers
If IsNumeric(txtLevel.Text) And IsNumeric(txtHealth.Text) Then
'The input is integer
Dim strName As String = txtCharacter.Text
Dim intLevel As Integer = txtLevel.Text
Dim intHealth As Integer = txtHealth.Text
Dim strStat As String = cmbStat.Text
MsgBox("choose a location to save in")
Else
'The input is not integer
MsgBox("Value is not an integer")
End If
Else
'A textbox is empty
MsgBox("you have not filled in all fields")
Me.Close()
End If

you can try with TryParse to be sure of integer value without error :
Dim intLevel As Integer
Dim intHealth As Integer
If (Integer.TryParse(txtLevel.Text, intLevel)) And (Integer.TryParse(txtHealth.Text, intHealth)) Then
MsgBox("choose a location to save in")
ElseIf String.IsNullOrWhiteSpace(txtHealth.Text) Or String.IsNullOrWhiteSpace(txtLevel.Text) Then
MsgBox("you have not filled in all fields")
Me.Close()
Else MsgBox("please input number form")
End If
Dim strName As String = txtCharacter.Text
Dim strStat As String = cmbStat.Text
find more about it on : Int32.TryParse Method

Related

When i try to login to a created account iy doesnt recognise the username, why is this?

Module Module1
Dim database As New Dictionary(Of String, String)
Dim ulist As New List(Of String)
Dim plist As New List(Of String)
Dim newname As String
Dim passw As String
Sub main()
menu() '
End Sub
Sub menu()
Console.WriteLine("type 1, 2 or 3")
Console.WriteLine("1 : create a new account")
Console.WriteLine("2: log in ")
Console.WriteLine("3 : quit program")
Dim choice As String
choice = Console.ReadLine()
If choice = "1" Then
create()
ElseIf choice = "2" Then
login()
ElseIf choice = "3" Then
Console.WriteLine("quitting...")
Console.Clear()
End If
End Sub
Sub login()
Dim unamever As String
Dim passwvari
Dim veri3 As Boolean = False
While veri3 = False
Console.WriteLine("please enter you username")
unamever = Console.ReadLine()
If ulist.Contains(unamever) Then
Console.WriteLine("please enter your password : ")
passwvari = Console.ReadLine()
If plist.Contains(passwvari) Then
Console.WriteLine("logging you in...")
veri3 = True
Else
Console.WriteLine("password incorrect try again")
veri3 = False
End If
Else
Console.WriteLine("username not registered try again")
veri3 = False
End If
End While
End Sub
Sub create()
Dim veri As Boolean = False
Dim attempts As Integer = 1
Do Until veri = True
Console.WriteLine("enter a new username")
newname = Console.ReadLine()
If ulist.Contains(newname) Then
Console.WriteLine("that username is already taken, try again")
attempts = attempts + 1
veri = False
Else
ulist.Add(newname)
Console.WriteLine("your new username has been stored")
notused()
veri = True
database.Add(newname, passw)
Console.WriteLine("succes you have made an account you username :" & newname & " and password: " & passw)
FileOpen(1, "C:\Users\iivix\OneDrive\Documents\A LEVEL\passws.txt", OpenMode.Output)
PrintLine(1, newname & passw)
End If
If attempts > 4 Then
Console.WriteLine("you have had more than 3 tries, BYE")
Console.Clear()
End If
Loop
End Sub
Sub notused()
Dim veri2 As Boolean = False
While veri2 = False
Console.WriteLine("create a password " & newname)
passw = Console.ReadLine
Dim passwlen = Len(passw)
If passwlen > 12 Then
Console.WriteLine("your password has been stored ")
plist.Add(passw)
veri2 = True
Else
Console.WriteLine("try again password must be greater than 12 characters")
veri2 = False
End If
End While
End Sub
End Module
This code is for a login system, I am a vb beginner and this is my code so far I have come across a problem: why aren't the usernames being stored when I try to log in later, how can I fix this? I want the user to be able to log back into an account when it is created another problem when writing usernames and passwords to a text file the new username overwrites the last, I want the usernames to be consecutively listed along with passwords'
BTW this isn't homework, its a beginners programming challenge
I have updated your code to use .net methods rather than obsolete VB6 methods. I made the LoginPath a Module level variable so it can be seen my all the methods in the Module. I am using a Dictionary rather than your 2 List(Of String)s. This way the username is the key and the password in the value. Dictionary lookup is very fast.
The first thing to do is to read the file and and fill the dictionary. If the file doesn't yet exist the user is informed.
The Create method changes a bit with the use of the Dictionary. I used the .net File class to write to the text file.
File.AppendAllLines(LoginPath, {$"{newname},{passw}"})
This is a very clever method. If the file doesn't exist, it creates it. It opens the file writes to the file and closes it. The first parameter is the path. The second parameter is what to write to the file, a String array. Notice the method names ends with AllLines, plural. The outer braces indicate that this is an array. Our array has only one element. I used an interpolated string indicated by the $ preceding the string. We can then insert variables directly into the string surrounded by braces. The comma is a literal in the string. We use the comma as a delimiter when the string is split into name and password.
Private LoginPath As String = "C:\Users\iivix\OneDrive\Documents\A LEVEL\passws.txt"
Private LoginDict As New Dictionary(Of String, String)
Sub Main()
ReadLoginFileAndFillDictionary()
menu()
Console.ReadKey()
End Sub
Private Sub Menu() 'Names of Subs, Functions etc. should begin with capital letters
Console.WriteLine("type 1, 2 or 3")
Console.WriteLine("1 : create a new account")
Console.WriteLine("2: log in ")
Console.WriteLine("3 : quit program")
Dim choice As String
choice = Console.ReadLine()
If choice = "1" Then
Create()
ElseIf choice = "2" Then
Login()
ElseIf choice = "3" Then
Console.WriteLine("quitting...")
Environment.Exit(0)
End If
End Sub
Private Sub Create()
Dim veri As Boolean 'Default value is False, value types initialize automatically
Dim attempts As Integer
Dim newname As String = ""
Dim passw As String = ""
Do Until veri = True
Console.WriteLine("enter a new username")
newname = Console.ReadLine()
If LoginDict.ContainsKey(newname) Then 'Searches the Keys in the Dictionary and returns True or False
Console.WriteLine("that username is already taken, try again")
attempts += 1 'new syntax for updating the value of a variable, saves a bit of typing
Else
veri = True
End If
If attempts > 4 Then
Console.WriteLine("you have had more than 3 tries, BYE")
Console.Clear()
Environment.Exit(0) 'To end the application
End If
Loop
veri = False 'You can use the same variable just reset its value
While veri = False
Console.WriteLine("create a password " & newname)
passw = Console.ReadLine
Dim passwlen = passw.Length 'Don't use the old VB6 Len
If passwlen > 12 Then
LoginDict.Add(newname, passw) 'Here is where the new user is added to the Dictionary
veri = True
Else
Console.WriteLine("try again, password must be greater than 12 characters")
End If
End While
Console.WriteLine("your new username and password have been stored")
Console.WriteLine("succes, you have made an account your username :" & newname & " and password: " & passw)
File.AppendAllLines(LoginPath, {$"{newname},{passw}"}) 'Adds the new user to the text file
End Sub
Private Sub Login()
Dim unamever As String = ""
Dim passwvari As String = ""
Dim veri As Boolean 'You don't need a different name for a variable in a another method.
While veri = False
Console.WriteLine("please enter you username")
unamever = Console.ReadLine()
If LoginDict.ContainsKey(unamever) Then 'Searches the Keys in the Dictionary and returns True or False
passwvari = LoginDict(unamever) 'Gets the value associated with the username
Console.WriteLine("please enter your password : ")
If passwvari = Console.ReadLine Then 'Compares the value found in the Dictionary to the string entered by the user.
Console.WriteLine("logging you in...")
veri = True
Else
Console.WriteLine("password incorrect, try again")
End If
Else
Console.WriteLine("username not registered, try again")
End If
End While
End Sub
Private Sub ReadLoginFileAndFillDictionary()
If File.Exists(LoginPath) Then
Dim lines = File.ReadAllLines(LoginPath) 'Read the file into an array of lines
For Each line In lines
Dim splits = line.Split(","c) 'Split each line by the comma into an array of 2 strings
LoginDict.Add(splits(0), splits(1)) 'The first element is the username and the second element is the password.
Next
Else
Console.WriteLine("There are currently no registered users. Please begin with Option 1.")
End If
End Sub
In a real application you would NEVER store passwords as plain text.

visual basic: Enter some numbers until a negative value is entered to stop the program

private Sub Command1_Click()
a = InputBox("What is the Number ?", "Input Example"," ")
If a = "-1" Then
End If
End Sub
the whole question is: Enter some numbers until a negative value is entered to stop the program(stop running the what is your number thing). then find the average of the entered numbers.
What I want to do, for now, I want to know how can I make my "a" variable accept any negative value like in the code above it stops when I enter -1 but I want to stop when I enter -3, -10, or any negative value.
There are some helpful answers down below
If you are expecting the usual input to be text then you can use the Double.TryParse method to check if a number was entered. If it was, then you can check if that number is negative, and exit the application if so:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry Form", "Enter your message here", 500, 700)
If userMsg <> "" Then
Dim x As Double
If Double.TryParse(userMsg, x) AndAlso x < 0 Then
Application.Exit()
End If
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub
The AndAlso operator only looks at the second argument if the first evaluated to True.
If you would like to repeat some portion of code till specific condition is met, you need to use:
While...End While Statement (Visual Basic)
or
Do...Loop Statement (Visual Basic)
It's also possible to write conditional loop using For... Next statement
Dim myNumber As Integer = 0
Dim mySum As Integer = 0
Dim myCounter As Integer = 0
Do
Dim answer As Object = InputBox("Enter integer value", "Getting average of integer values...", "")
'check if user clicked "Cancel" button
If answer <> "" Then
'is it a number?
If Int32.TryParse(answer, myNumber)
If myNumber >=0 Then
mySum += myNumber
myCounter += 1
Else
Exit Do
End If
End If
End If
Loop
Dim average As Double = mySum/myCounter
'you can display average now
Tip: Do not use InputBox, because this "control" is VisualBasic specific. Use custom Form instead. There's tons of examples on Google!

I want to save a file in VB.net from the amount of tries a user has

I'm a student trying to learn Console App .Net Framework and I want to code a random number between 0000 and 9999 (as a pin that you need to guess). Thus far I've had to set it as a random number from 1000 to 9999 as the system wont let me do 0000. Furthermore, I want to save the amount of tries the user has as a text file e.g. if the user tries 50 times, I'd like it to say
Username Tries
I've tried Randomise() Rnd(*9999) and X = EasyNum.Next(1000, 9999) but then I can't compare unless I convert that to an integer.
Module Module1
Dim Tries As String = 0
Dim EasyNum As New Random
Dim HardNum As New Random
Dim Attempt As String
Sub Main()
Dim Difficulty As String
Console.WriteLine("Welcome to MasterMind")
Console.WriteLine("Choose between Easy and Hard difficulty")
Difficulty = Strings.LCase(Console.ReadLine)
While Difficulty <> "easy" And Difficulty <> "hard"
Console.WriteLine("That's not a correct mode")
Difficulty = Strings.LCase(Console.ReadLine)
End While
If Difficulty = "easy" Then
Easy()
ElseIf Difficulty = "hard" Then
Hard()
End If
End Sub
Dim EasyGuess1 As Integer
Dim EasyGuess2 As Integer
Dim X As String
Dim Y As Integer
Sub Easy()
Console.WriteLine("You have chosen the easy difficulty")
Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
Console.WriteLine("Enter your guess")
X = EasyNum.Next(1000, 9999)
Console.WriteLine(X)
EasyGuess1 = Console.ReadLine
Tries = +1
If Mid(CStr(EasyGuess1), 1, 1) = Mid(CStr(X), 1, 1) Then
Console.WriteLine("You have 1 number correct, try again?")
Attempt = Strings.LCase(Console.ReadLine)
While Attempt <> "yes" And Attempt <> "no"
Console.WriteLine("Enter either yes or no")
Attempt = Strings.LCase(Console.ReadLine)
End While
ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
Console.WriteLine("You have 1 number correct, try again?")
Attempt = Strings.LCase(Console.ReadLine)
While Attempt <> "yes" And Attempt <> "no"
Console.WriteLine("Enter either yes or no")
Attempt = Strings.LCase(Console.ReadLine)
End While
End If
If Attempt = "yes" Then
EasyYes()
ElseIf Attempt = "no" Then
EasyNo()
End If
Console.WriteLine("incorrect")
Console.ReadKey()
End Sub
Sub EasyYes()
Console.WriteLine("Enter a new guess")
EasyGuess1 = Console.ReadLine
End Sub
Sub EasyNo()
Dim Save As String
Dim File As System.IO.File
Console.WriteLine("Do you want to save your tries? Enter Yes or no")
Save = Strings.LCase(Console.ReadLine)
If Save = "yes" Then
System.IO.File.Create(Tries, "C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test")
End If
End Sub
Sub Hard()
Console.WriteLine("You have chosen the hard difficulty")
End Sub
Sub HardYes()
End Sub
Sub HardNo()
End Sub
End Module
When I try to save the tries, I get this:
System.InvalidCastException: 'Conversion from string "C:\X\Code\VB\Challenges\Cha" to type 'Integer' is not valid.'
InnerException
FormatException: Input string was not in a correct format.
Which I don't understand myself.
Comments in line. Please read all comments. This program is still not working too well but I will leave it to you to tidy up.
Module Module1
Dim Tries As Integer = 0
'Use only a single instance of Random
Dim EasyNum As New Random
'Dim HardNum As New Random
Dim Attempt As String
Sub Main()
Dim Difficulty As String
Console.WriteLine("Welcome to MasterMind")
Console.WriteLine("Choose between Easy and Hard difficulty")
Difficulty = Strings.LCase(Console.ReadLine)
'AndAlso prevents the second condition from executing if the first condition is true
While Difficulty <> "easy" AndAlso Difficulty <> "hard"
Console.WriteLine("That's not a correct mode")
Difficulty = Strings.LCase(Console.ReadLine)
End While
If Difficulty = "easy" Then
Easy()
'ElseIf Difficulty = "hard" Then
' Hard() 'Not implemented
End If
End Sub
'Dim EasyGuess2 As Integer
'Dim X As String
'Dim Y As Integer
Sub Easy()
Dim EasyGuess1 As Integer
Console.WriteLine("You have chosen the easy difficulty")
Console.WriteLine("You have to guess a 4 Digit number between 1000 and 9999")
Console.WriteLine("Enter your guess")
'X = EasyNum.Next(1000, 9999)
'The next method returns a non-negative integer not a string
'To get 0 to 9999 with leading zeros do the following
'Returns a non-negative random integer that is less than the specified maximum.
Dim X = EasyNum.Next(10000).ToString("0000")
Console.WriteLine(X)
'Console.ReadLine returns a String. You should Not assign a String to an Integer
'EasyGuess1 = Console.ReadLine
'Never trust a user :-) Use .TryParse to set the variable
Integer.TryParse(Console.ReadLine, EasyGuess1)
'This just assigns the value of 1 to Tries
'Tries = +1
'If you want to increment Tries
Tries += 1
'Let's compare apples and apples
'If you just convert EasyGuess1 To a string and EasyGuess1 is 54
'the string is "54" You want a 4 character string
'If Mid(EasyGuess1.ToString("0000"), 1, 1) = Mid(CStr(X), 1, 1) Then
' 'but you only compared the first character, what about the rest?
' 'Mid is aroung for backward compatibility. It should not be used for new code.
' 'The position Integer is one based which is not at all sympatico with .net
' Console.WriteLine("You have 1 number correct, try again?")
' Attempt = Strings.LCase(Console.ReadLine)
' While Attempt <> "yes" And Attempt <> "no"
' Console.WriteLine("Enter either yes or no")
' Attempt = Strings.LCase(Console.ReadLine)
' End While
'ElseIf Mid(CStr(EasyGuess1), 2, 1) = Mid(CStr(X), 2, 1) Then
' Console.WriteLine("You have 1 number correct, try again?")
' Attempt = Strings.LCase(Console.ReadLine)
' While Attempt <> "yes" And Attempt <> "no"
' Console.WriteLine("Enter either yes or no")
' Attempt = Strings.LCase(Console.ReadLine)
' End While
'End If
Dim CorrectCharacters = TestInput(EasyGuess1, X)
Console.WriteLine($"You have guessed {CorrectCharacters} correctly. Try again?")
'Use the .net way. The framework is available to all languages in .net
'so it will be easier to learn other languages.
Attempt = (Console.ReadLine).ToLower
If Attempt = "yes" Then
EasyYes()
ElseIf Attempt = "no" Then
EasyNo()
End If
Console.WriteLine("incorrect")
Console.ReadKey()
End Sub
Sub EasyYes()
Dim guess As Integer
Console.WriteLine("Enter a new guess")
'You are doing this twice ???
'EasyGuess1 = Console.ReadLine
Integer.TryParse(Console.ReadLine, guess)
'EasyGuess1 will be 0 if the entry is other than an integer
'Very nice bu this Sub doesn't do anything
End Sub
Sub EasyNo()
Dim Save As String
'Unused local variable and if you needed this it is a poor choice for a variable name
'Dim File As System.IO.File
Console.WriteLine("Do you want to save your tries? Enter Yes or no")
Save = Console.ReadLine.ToLower
If Save = "yes" Then
'Give the file name an extension.
'When you pass (String, Integer) to the Create method, the Integer is the number of bytes
'buffered for reads And writes to the file.
'Not exactly what you were expecting.
'System.IO.File.Create("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test.txt", Tries)
'Imports System.IO at top of file
File.WriteAllText("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test.txt", Tries.ToString)
End If
End Sub
Sub Hard()
Console.WriteLine("You have chosen the hard difficulty")
End Sub
Private Function TestInput(Guessed As Integer, RandString As String) As Integer
Dim Correct As Integer
Dim Guess As String = Guessed.ToString("0000")
'A String can be a Char array
'Here we check each character in the 2 strings for equality
'and if true then increment Correct
For i = 0 To 3
If Guess(i) = RandString(i) Then
Correct += 1
End If
Next
Return Correct
End Function
End Module
There are a lot of issues, but I don't want to spoil it for you.
I definitely recommend to put "Option Strict On" in the project settings, so you immediately see where there are conversion errors (a string assigned to a integer etc).
To save the file, it should be something like
If Save = "yes" Then
File.WriteAllText("C:\X\Code\VB\Challenges\Challenge 1\MasterMind Test", Tries.ToString())
End If
(there are also File.Append... functions).
The Random class is a bit tricky, this is an object that provides random values and is not yet the random value itself. Always use the same random object for all different numbers, otherwise you might get the same number:
Private Randomizer As New Random(Environment.TickCount)
Private EasyNum As Int32 = Randomizer.Next(0, 10000) '0 to 9999
Private HardNum As Int32 = Randomizer.Next(0, 100000) '0 to 99999
The "from" value of the randomizer's Next method is always inclusive, the "to" value exclusive, for whatever reasons.
To increment a variable, the syntax is
Tries += 1
instead of "Tries = +1"
To write a number with leading digits, use might use
Console.Out.WriteLine($"The correct solution would have been: {EasyNum:0000}")
or
EasyNum.ToString("0000")

Check if null VB.NET

having trouble working out why this won't check the textbox too as well as the selected color. If I do not put a color it flags up the "please enter fields" message, however if I do select a color but do not put anything in the name textbox then it carries on and just outputs a blank string in the msgbox.
Code is:
Dim newColor As Color
Dim userName As String
Dim notEnoughArguments As String = "Please fill out the fields"
'Click event for button
Private Sub enterBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enterBtn.Click
If (userName Is "") Then
MsgBox(notEnoughArguments)
ElseIf (userName Is "" And colorLtb.SelectedItem Is Nothing) Then
MsgBox(notEnoughArguments)
ElseIf (colorLtb.SelectedItem Is Nothing) Then
MsgBox(notEnoughArguments)
Else
userName = txt1.Text
Dim selectedColor As String = colorLtb.SelectedItem.ToString
newColor = Color.FromName(selectedColor)
Dim msgBoxText As String = "Hello " + txt1.Text + "." & vbCrLf + "Changing your color to " + selectedColor + "."
MsgBox(msgBoxText)
Me.BackColor = newColor
End If
End Sub
For strings (like your textbox contents) use String.IsNullOrWhitespace as a test. Also you want both arguments, right? So a single statement should do:
If String.IsNullOrEmpty(userName) OrElse colorLtb.SelectedItem Is Nothing Then
MessageBox.Show(notEnoughArguments)
Return
End If
The problem is that Dim userName As String means the variable has nothing at all and that is not the same as an empty string. I always declare strings and immediately set them to String.Empty to avoid null reference exceptions, but using String.IsNullOrEmpty is a clean and robust way to test the contents of a string variable.
Normally to test for equality in VB, you use a single = rather than Is
If (userName = "") Then
When testing for Nothing, you have to use Is
If (userName Is Nothing) Then
IsNullOrEmpty combines both tests. As the accepted answer suggests:
If (String.IsNullOrEmpty(userName)) Then

DMin in VBA returns wrong value from query

im trying to use vba in an access project of mine but when I use the DMin function to find the smallest value in a query I instead get the current value of the form I have created returned.
The Dmin function does work correctly when I run it outside the context of the code but I get the problem I described above when I try to use it in my code.
I cant seem to understand the formatting on StackExchange so here is a pastebin of the code instead.
http://pastebin.com/XCNPfNYG
The problem line is here
PastPrice = DMin([Price Each], "qryBoxHistory", "[CalConcatID] = 133377")
Option Compare Database
Option Explicit
Private Sub Save_Click()
Dim CurrentConcat As String
Dim PastConcat As String
Dim PastConcatGrab As Boolean
Dim txtbox As String
Dim PastPrice As Currency
Dim ExpPrice As Currency
CurrentConcat = Me!CurrentConcat 'Set current Concatenated ID to the ID on the form
PastConcatGrab = IsNull(DLookup("[CalConcatID]", "qryBoxHistory", "[CalConcatID] = CurrentConcat"))
If PastConcatGrab = True Then 'If lookup shows that no boxes have been entered under that ID then a message is displayed and the values saved
txtbox = MsgBox("This is a new box, no past prices exist", vbOKOnly, "Information")
DoCmd.RunCommand acCmdSaveRecord
Else
PastConcat = DLookup("[CalConcatID]", "qryBoxHistory", "[CalConcatID] = CurrentConcat")
PastPrice = DMin([qryBoxHistory]![Price Each], "qryBoxHistory", "[CalConcatID] = 133377")
ExpPrice = Me![Price]
If ExpPrice > PastPrice Then
txtbox = MsgBox("This Box is not being supplied at a discounted rate, box has NOT been saved", vbOKOnly, "Information")
Else
txtbox = MsgBox("This box is discounted, This price has been saved", vbOKOnly, "Information")
End If
End If
End Sub
You appear to be missing the necessary quotes:
DMin("[Price Each]", "qryBoxHistory", "[CalConcatID] = 133377"