Nested If / Else - vb.net

So I have a sub on a button click that does the following:
If the text entry within a combo box (cmbServerInstall.Text) is blank, firstly it will force the user to make a selection before proceeding.
Else, a string (strGameServer) is populated with the text within the combo box (cmbServerInstall.Text).
From here, a MessageBox will then show with a Yes/No option, asking if the user wishes to proceed.
Here is where things are going wrong.
What I want to happen
If the user selects yes, then I want to use another if/else to determine what was stored in the string strGameServer. Depending on what this is set to, it will launch one of two batch files (I understand the file paths are the same at the moment, I plan to update this at a later date).
If the user selects no, I want it to remove the selection from the combobox cmbServerInstall.
What is happening as it stands
Basically the shell command launches the batch file REGARDLESS of whether or not MsgBoxResult is Yes or No.
Could anyone kindly take a look at the code below and point me in the direction of where I am going wrong? Nested IFs seem to be getting the better of me.
Dim strGameServer As String
If cmbServerInstall.Text = "" Then
MessageBox.Show("Please select a game server to install", "No game server selected", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
Else
strGameServer = cmbServerInstall.Text
MessageBox.Show("You have chosen" + " " + strGameServer + "." + " " + "Please confirm you wish to proceed with your selection.", "Confirm game server selection", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
If MsgBoxResult.Yes Then
If strGameServer = "Counter-Strike: Global Offensive" Then
Shell("C:\Users\Damon\Desktop\YorkshaLAN Server Creator\YorkshaLAN Server Setup.bat", AppWinStyle.NormalFocus)
Else : strGameServer = "Team Fortress 2"
Shell("C:\Users\Damon\Desktop\YorkshaLAN Server Creator\YorkshaLAN Server Setup.bat", AppWinStyle.NormalFocus)
End If
Else
cmbServerInstall.Text = ""
End If
cmbServerInstall.Text = ""
cmbServerInstall.Enabled = False
btnServerGoInstall.Enabled = False
End If
End Sub

You need to save the result from MessageBox.Show and then check it, or do so in one line.
Edit of original code:
If cmbServerInstall.Text = "" Then
MessageBox.Show("Please select a game server to install", "No game server selected", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
Else
Dim strGameServer As String = cmbServerInstall.Text ' Moved init to avoid declaration without use '
If MessageBox.Show("You have chosen" & " " & strGameServer & "." & " " & "Please confirm you wish to proceed with your selection.",
"Confirm game server selection",
MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) =MsgBoxResult.Yes Then
If strGameServer = "Counter-Strike: Global Offensive" Then
Shell("C:\Users\Damon\Desktop\YorkshaLAN Server Creator\YorkshaLAN Server Setup.bat", AppWinStyle.NormalFocus)
Else
strGameServer = "Team Fortress 2"
Shell("C:\Users\Damon\Desktop\YorkshaLAN Server Creator\YorkshaLAN Server Setup.bat", AppWinStyle.NormalFocus)
End If
Else
cmbServerInstall.Text = ""
End If
cmbServerInstall.Text = ""
cmbServerInstall.Enabled = False
btnServerGoInstall.Enabled = False
End If
End Sub

You need to get the result of the MessageBox with the question and check the result
Dim result = MessageBox.Show("You have chosen ......")
If result = MsgBoxResult.Yes Then
.....
Actually your code checks the enum MsgBoxResult.Yes and because it is not zero the if is always evaulated as true
Also, if I were you I would try to remove any usage of the old VB6 syntax and enumerations. Actually MessageBox.Show returns a DialogResult enumeration not a MsgBoxResult. This is here just for VB6 compatibility
Dim result = MessageBox.Show("You have chosen ......")
If result = DialogResult.Yes Then

Related

Required Fields Before Update in Conjunction with Close Button

Novie VBA programmer here, looking for the ABC's direction.
I have 3 fields that I need to require in a form before the form is close.
I had previously require the fields within the Table; However, when I create a new contact to add to this Form I need to Requery the results of the added contact. When I Requery and the required fields are Required from the Table I reach a stuck, since I need to add the new contact but cannot Requery until the fields are filled (and I cannot do that until I have the right contact).
I know this is in the wrong place but this is the code I have thus far attached to my "Close" button.
Private Sub SaveCloseBtn_Click()
If Nz([PlaintiffName], "") = "" Then
MsgBox "Plaintiff Name is required.", vbExclamation, "Required Field"
Cancel = True
End If
If Nz([LawFirm], "") = "" Then
MsgBox "Law Firm is required.", vbExclamation, "Required Field"
Cancel = True
Me.[LawFirm].SetFocus
End If
If [PlaintiffName] = True Then
If [LawFirm] = True Then
If MsgBox("You are about to exit this case. Are you sure?", vbYesNo, "Warning!") = vbYes Then
DoCmd.Close
Else
DoCmd.CancelEvent
End If
End Sub
I tried creating Required fields in "BeforeUpdate" but for whatever reason, it does not work in conjunction with the docmd.close form function.

VBA code works in one Access Database, but not another. All of the supporting objects have been imported. What I am not seeing?

This code is for a login form I have setup to enter the front end copy of a database. In one database it works like a charm. I imported the form and corresponding objects to another database and it appears to be not recognizing my password when I enter it. I just keep getting the message box I have popping up that says, "Incorrect password". Any help figuring this out would be greatly apprecaited.
The SQL statement that drives the cboUser combo box on the login form is:
SELECT tblUser.UserID, [FName] & " " & [LName] AS Fullname,
tblUser.Password, tblUser.PWReset, tblUser.AccessLevelID
FROM tblUser ORDER BY tblUser.LName, tblUser.FName;
.
Private Sub OkBTN_Click()
Static intIncorrectCount As Integer
Dim AuthorityNumber As Integer
'Dim rs As Recordset
'TempVars("Username") = Me.cboUser.Value
'Column references for cbouser row source reference
'UserID = 0
'FullName = 1
'Password = 2
'PWReset = 3
'AccessLevelID = 4
'Set rs = CurrentDb.OpenRecordset("UserNameQuery", dbOpenSnapshot)
'N = Nz(DLookup("Fullname", "UserNameQuery", "Fullname=""" & Me.cboUser & """"), " ")
'Check that User is selected
If IsNull(Me.cboUser) Then
MsgBox "You forgot To Select your name from the drop down menu!", vbCritical
Me.cboUser.SetFocus
Else
'Check for correct password
If Me.txtPassword = Me.cboUser.Column(2) Then
'Check if password needs to be reset
If Me.cboUser.Column(3) Then
DoCmd.OpenForm "frmPasswordChange", , , "[UserID] = " & Me.cboUser
End If
Me.Visible = FALSE
intIncorrectCount = 0
'Main menu after correct login based on AuthorityNumber
If Me.cboUser.Column(4) = 5 Then
DoCmd.OpenForm "SRL1MainMenu"
'Forms!AMSReportForm!L2Menubtn.Visible = False
Forms!SRL1MainMenu!FullNameLoggedIn = Forms!frmLogin!cboUser.Column(1)
Else
DoCmd.OpenForm "L2MainMenu2"
'Forms!AMSReportForm!L2Menubtn.Visible = True
Forms!L2MainMenu2!FullNameLoggedIn = Forms!frmLogin!cboUser.Column(1)
End If
'Failed login attempt limitation
ElseIf intIncorrectCount > 1 Then
MsgBox "Too many failed login attempts. Click OK To Set New password", vbOK + vbExclamation
DoCmd.OpenForm "frmPasswordChange", , , "[UserID] = " & Me.cboUser
'DoCmd.Close acForm, "frmLogin"
Else
MsgBox "Incorrect password", vbOKOnly + vbExclamation
Me.txtPassword = Null
Me.txtPassword.SetFocus
intIncorrectCount = intIncorrectCount + 1
End If
End If
End Sub
First, #Andre is probably right - you may have to apply brackets to "Password".
Next, this may not perform a case sensitive comparison:
If Me.txtPassword = Me.cboUser.Column(2) Then
Use StrComp to do that:
If StrComp(Me!txtPassword.Value, Me!cboUser.Column(2), vbBinaryCompare) = 0 Then
Finally, you should never store plain passwords; store a hash value instead. It isn't that difficult, if you study my latest article:
Storing passwords in VBA using the Microsoft NG Cryptography (CNG) API

MS Access: Why is my error message appearing immediately after entry?

I have created a form where I enter in faculty information and I made error messages appear if certain fields are missing.
However, as soon as I click save, the form saves the entry like I wanted, but also immediately generates the error messages I created, even though I didn't have a chance to enter anything new into the fields. My code is this...
' Click event for Save button
Private Sub cmdSave_Click()
' ToDo fix the labels in this function so they match the function name. Just cosmetic.
On Error GoTo Add_Faculty_Click_Err
On Error Resume Next
DoCmd.GoToRecord , "", acNewRec
' Error handling for FirstName
Dim OKToSave As Boolean
OKToSave = True
If Not SomethingIn(Me.FirstName) Then ' Null
Beep
MsgBox "A first name is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.Combo17) Then
Beep
MsgBox "A department is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.LastName) Then
Beep
MsgBox "A last name is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.Text19) Then
Beep
MsgBox "A user name is required", vbOKOnly, "Missing Information"
OKToSave = False
Else
Dim myUserName As String
myUserName = "UserName = " + Chr(34) + Me.Text19 + Chr(34)
If DLookup("UserName", "tFaculty", myUserName) <> Null Then
MsgBox "User name already on file", vbOKOnly, "User name already on file."
OKToSave = False
End If
End If
If OKToSave Then
' If we get this far, all data is valid and it's time to save
DoCmd.RunCommand acCmdSaveRecord
' ToDo refresh and synch combo box
Me.cbFacultyID = Me.FacultyID
' ToDo hide save and cancel buttons
Me.cmdSave.Visible = False
Me.cmdCancel.Visible = False
' ToDo show Add and delete buttons
Me.[Add Faculty].Visible = True
Me.Delete.Visible = True
End If
Add_Faculty_Click_Exit:
Exit Sub
Add_Faculty_Click_Err:
Resume Add_Faculty_Click_Exit
End Sub
I thought I fixed things with the OKToSave portion, but its not working. What is causing this?
The very first thing your handler does is move to a new record:
DoCmd.GoToRecord , "", acNewRec
That saves the record. Nothing after that matters. So remove that line.
Replace the line:
DoCmd.RunCommand acCmdSaveRecord
With this instead:
Me.Dirty = False
DoCmd.GoToRecord , "", acNewRec
This will make it so you won't save and move the current record until it's OKToSave

How to refill combobox with similar records based on what user types

I'm currently building a form where a user can look up a tool based on the description or part number.
I want user to be able to type any letters into the combobox that I have tied to a query listing all my tools and the combobox will repopulate itself with the tools most similar to what is present in their combobox. For example, if they start typing wre, then tools that have similar characters will start appearing in the combobox such as wrench, torque wrench, power wrench, etc.
I've tried looking around for other people's solutions to this but either I didn't fully comprehend the existing solution (I'm fairly new to Access) or it wasn't what I was looking for. I've seen that people suggested using a listbox instead but I really don't want to go down that route.
I was thinking about using what the user types in the combobox and my VBA code will pick up the "change event" and requery the combobox on the fly by using their input as the like criteria for the new query.
Is this a possible route? Will it be slower? Is there a better route?
I'm hoping someone can show some examples on how to achieve what I'm looking for.
The search as you type feature is very useful! With a textbox and a listbox, you can setup a dynamic search tool that will filter a list for approximate matches as you type. The textbox has four events associated with it, as seen here.
The code behind the form looks like this. Pay attention to the part in bold. This is where we create a string of SQL commands, and utilize the SQL Like operator, to get dynamic matches as we type. Pay attention to the text in bold below.
Option Compare Database
Option Explicit On
Private blnSpace As Boolean 'INCLUDE THIS LINE ON YOUR FORM
Private Sub btnClearFilter_Click()
'CODE FOR THE RED "X" BUTTON TO CLEAR THE FILTER AND SHOW ALL
On Error Resume Next
Me.txtSearch.Value = ""
txtSearch_Change()
End Sub
Private Sub txtSearch_Change()
'CODE THAT HANDLES WHAT HAPPENS WHEN THE USER TYPES IN THE SEARCH BOX
Dim strFullList As String
Dim strFilteredList As String
If blnSpace = False Then
Me.Refresh 'refresh to make sure the text box changes are actually available to use
'specify the default/full rowsource for the control
strFullList = "SELECT RecordID, First, Last FROM tblNames ORDER BY First;"
'specify the way you want the rowsource to be filtered based on the user's entry
strFilteredList = "SELECT RecordID, First, Last FROM tblNames WHERE [First] LIKE ""*" & Me.txtSearch.Value &
"*"" OR [Last] LIKE ""*" & Me.txtSearch.Value & "*"" ORDER BY [First]"
'run the search
fLiveSearch Me.txtSearch, Me.lstItems, strFullList, strFilteredList, Me.txtCount
End If
End Sub
Private Sub txtSearch_KeyPress(KeyAscii As Integer)
'NECESSARY TO IDENTIFY IF THE USER IS HITTING THE SPACEBAR
'IN WHICH CASE WE WANT TO IGNORE THE INPUT
On Error GoTo err_handle
If KeyAscii = 32 Then
blnSpace = True
Else
blnSpace = False
End If
Exit Sub
err_handle:
Select Case Err.Number
Case Else
MsgBox "An unexpected error has occurred: " & vbCrLf & Err.Description &
vbCrLf & "Error " & Err.Number & "(" & Erl() & ")"
End Select
End Sub
Private Sub txtSearch_GotFocus()
' USED TO REMOVE THE PROMPT IF THE CONTROL GETS FOCUS
On Error Resume Next
If Me.txtSearch.Value = "(type to search)" Then
Me.txtSearch.Value = ""
End If
End Sub
Private Sub txtSearch_LostFocus()
' USED TO ADD THE PROMPT BACK IN IF THE CONTROL LOSES FOCUS
On Error Resume Next
If Me.txtSearch.Value = "" Then
Me.txtSearch.Value = "(type to search)"
End If
End Sub
Finally, in a regular module, you will need this script.
Option Compare Database
Option Explicit On
'************* Code Start **************
' This code was originally written by OpenGate Software
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
' OpenGate Software http://www.opengatesw.net
Function fLiveSearch(ctlSearchBox As TextBox, ctlFilter As Control,
strFullSQL As String, strFilteredSQL As String, Optional ctlCountLabel As Control)
Const iSensitivity = 1 'Set to the number of characters the user must enter before the search starts
Const blnEmptyOnNoMatch = True 'Set to true if you want nothing to appear if nothing matches their search
On Error GoTo err_handle
'restore the cursor to where they left off
ctlSearchBox.SetFocus
ctlSearchBox.SelStart = Len(ctlSearchBox.Value) + 1
If ctlSearchBox.Value <> "" Then
'Only fire if they've input more than two characters (otherwise it's wasteful)
If Len(ctlSearchBox.Value) > iSensitivity Then
ctlFilter.RowSource = strFilteredSQL
If ctlFilter.ListCount > 0 Then
ctlSearchBox.SetFocus
ctlSearchBox.SelStart = Len(ctlSearchBox.Value) + 1
Else
If blnEmptyOnNoMatch = True Then
ctlFilter.RowSource = ""
Else
ctlFilter.RowSource = strFullSQL
End If
End If
Else
ctlFilter.RowSource = strFullSQL
End If
Else
ctlFilter.RowSource = strFullSQL
End If
'if there is a count label, then update it
If IsMissing(ctlCountLabel) = False Then
ctlCountLabel.Caption = "Displaying " & Format(ctlFilter.ListCount - 1, "#,##0") & " records"
End If
Exit Function
err_handle:
Select Case Err.Number
Case 91 'no ctlCountLabel
'exit
Case 94 'null string
'exit
Case Else
MsgBox "An unexpected error has occurred: " & vbCrLf & Err.Description &
vbCrLf & "Error " & Err.Number & vbCrLf & "Line: " & Erl()
End Select
End Function
The code comes from this link:
http://www.opengatesw.net/ms-access-tutorials/Access-Articles/Search-As-You-Type-Access.html

VB compile error when trying to use String.Compare

I am trying to check if the password is the same or not (in terms of caps too) using vb.net. But the line
result = String.Compare(actPassword,userPassword)
keep giving error "Compile Error: Expected:("
Private Sub Login_Click()
'Check to see if data is entered into the UserName combo box
If IsNull(Me.cmbLoginID) Or Me.cmbLoginID = "" Then
MsgBox "You must enter a User Name.", vbOKOnly, "Required Data"
Me.cmbLoginID.SetFocus
Exit Sub
End If
'Check to see if data is entered into the password box
If IsNull(Me.txtPW) Or Me.txtPW = "" Then
MsgBox "You must enter a Password.", vbOKOnly, "Required Data"
Me.txtPW.SetFocus
Exit Sub
End If
'Check value of password in tblEmployees to see if this matches value chosen in combo box
Dim userPassword As String
Dim actPassword As String
Dim result As Integer
userPassword = txtPW.Text
actPassword = DLookup("EmpPassword", "Employee", "EmployeeID='" + Me.cmbLoginID.Value + "'")
result = String.Compare(actPassword,userPassword)
If result = -1 Then
'Close logon form and open splash screen
DoCmd.Close acForm, "Login", acSaveNo
DoCmd.OpenForm "HomePage"
Else
MsgBox "Password Invalid. Please Try Again", vbCritical + vbOKOnly, "Invalid Entry!"
Me.txtPW.SetFocus
End If
'If User Enters incorrect password 3 times database will shutdown
intLogonAttempts = intLogonAttempts + 1
If intLogonAttempts > 3 Then
MsgBox "You do not have access to this database. Please contact your system administrator.", vbCritical, "Restricted Access!"
Application.Quit
End If
End Sub
That's because there is no String.Compare() in VBA (There is in VB.NET)
Also, please note VB.NET is not VBA
Use StrComp
Use StrComp
result = StrComp(actPassword, userPassword, vbTextCompare)
While String.Compare() exists in VB.Net, I don't think it does in VBA. In any case, what you're doing is wrong anyway.
String.Compare can return any integer and it will only return zero if they match. Your particular test (comparing against -1) is only checking one possibility, that the actual password is less than the desired one, and it's only checking for one of the possible negative values.
You would be better off in that case with something like:
if result <> 0 Then
However, if you just want to compare two strings for equality in VBA (rather than figure out the relative ordering), you can just use:
if actPassword = userPassword Then