This question is continued from here: Add user input to Excel table upon upload to Access database
Now that I have my fields connected to a table in my database, I want to make sure that everyone fills them in. Upon clicking the Import button, I want to check the fields (SANumber, SerialNumber, CustomerName, and LyoSize) to make sure it will be a 'valid upload'.
I have this code so far:
Function CheckInputs() As Boolean
If Me.SANumber.value Or Me.SerialNumber.value Or Me.CustomerName.value Or Me.LyoSize.value = Null Then
CheckInputs = True
Else
CheckInputs = False
End If
End Function
'Import MCL Files Code
Private Sub ImportMCL_Click()
On Error GoTo ErrorHandler
'disable ms access warnings
DoCmd.SetWarnings False
Call CheckInputs
If CheckInputs = True Then
MsgBox "All inputs must be entered!"
Exit Sub
Else
'load spreadsheet in .xls format
DoCmd.TransferSpreadsheet acImport, 8, "_MCL_UPLOAD", selectFile(), True
DoCmd.OpenQuery "UpdateMCL"
Call InsertInto_MASTER_UPLOAD
Call Delete_MCL_UPLOAD
MsgBox "MCL Imported Successfully!"
're-enable ms access warnings
DoCmd.SetWarnings True
End If
Exit Sub
ErrorHandler:
MsgBox "There was an Error: " & Err & ": " & Error(Err)
End Sub
It should work, but keeps on giving me the
ERROR: 13. Type Mismatch
You need to specifically check each field for null - you cannot do it this way:
If Me.SANumber.value Or Me.SerialNumber.value Or _
Me.CustomerName.value Or Me.LyoSize.value = Null Then
Something like
If IsNull(Me.SANumber) Or IsNull(SerialNumber) Or _
IsNull(Me.CustomerName) Or IsNull(Me.LyoSize) = Null Then
You should rename your function to something like "EmptyInputs" to make your code a little more self-documenting. "CheckInputs" is a little non-descriptive.
You CheckInputs() functions logic is incorrect. Or will return true if any one condition is meet. To get your desired result you can either ask does:
If Condition1 = true AND Condition2 = true AND ....
Otherwise you can ask If Condition1 = false OR Condition2 = false OR ....
Try this....
Function isFormValid() As Boolean
If isTextFieldInvalid(Me.SANumber) Or isTextFieldInvalid(Me.SerialNumber) Or isTextFieldInvalid(Me.CustomerName.Value) Or Me.LyoSize.Value = Null Then
isFormValid = False
Else
isFormValid = True
End If
End Function
Function isTextFieldInvalid(FieldControl) As Boolean
If Not IsNull(FieldControl) Then
If Len(Trim(FieldControl.Value)) Then
isFieldValid = True
End If
End If
End Function
'Import MCL Files Code
Private Sub ImportMCL_Click()
On Error GoTo ErrorHandler
'disable ms access warnings
DoCmd.SetWarnings False
If isFormValid Then
MsgBox "All inputs must be entered!"
Exit Sub
Else
'load spreadsheet in .xls format
DoCmd.TransferSpreadsheet acImport, 8, "_MCL_UPLOAD", selectFile(), True
DoCmd.OpenQuery "UpdateMCL"
Call InsertInto_MASTER_UPLOAD
Call Delete_MCL_UPLOAD
MsgBox "MCL Imported Successfully!"
're-enable ms access warnings
DoCmd.SetWarnings True
End If
Exit Sub
ErrorHandler:
MsgBox "There was an Error: " & Err & ": " & Error(Err)
End Sub
Also, if you're clearing out afterwards by going something like SANumber = "" then testing for Nulls might not work. I'd check for both nulls and blanks. This is a general template you could use.
Dim LResponse As Integer
If (Nz(Me.SANumber.Value) = "") Then
MsgBox "Please enter a SA Number.", vbCritical + vbOKOnly, "Error"
ElseIf (Nz(Me.SerialNumber.Value) = "") Then
MsgBox "Please enter a Serial Number.", vbCritical + vbOKOnly, "Error"
'All criteria met
Else
LResponse = MsgBox("Would you like to submit? ", vbQuestion + vbYesNo, "Question")
If LResponse = vbYes Then
'enter code here
ElseIf LResponse = vbNo Then
MsgBox ("Not submitted.")
End If
End If
Related
My intent is to deny users that do not meet a certain access level access to forms. I initially had issues with error code 3265 while writing the code for:
TempVars("EmployeeType").Value = rs!EmployeeType_ID.Value
This is no longer an issue; however, I cannot get access to the form even when the appropriate user is trying to enter. I've checked the spelling of table and column names multiple times as well.
Below is my code for the login (where I'm using the tempvars), followed by the code in form Load().
Option Compare Database
Option Explicit
Private Sub btnLogin_Click()
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("Employees", dbOpenSnapshot, dbReadOnly)
rs.FindFirst "UserName='" & Me.txtUserName & "'"
If rs.NoMatch = True Then
Me.lblWrongUser.Visible = True
Me.txtUserName.SetFocus
Exit Sub
End If
Me.lblWrongUser.Visible = False
If rs!Password <> Me.txtPassword Then
Me.lblWrongPass.Visible = True
Me.txtPassword.SetFocus
Exit Sub
End If
If IsNull(Me.txtUserName) Or IsNull(Me.txtPassword) Then
MsgBox "You must enter password or login ID.", vbOKOnly + vbInformation, "Required Data"
Me.txtUserName.SetFocus
Exit Sub
End If
Me.lblWrongPass.Visible = False
If rs!EmployeeType >= 4 Then
Dim prop As Property
On Error GoTo SetProperty
Set prop = CurrentDb.CreateProperty("AllowBypassKey", dbBoolean, False)
TempVars("UserName").Value = Me.txtUserName.Value
TempVars("EmployeeType").Value = rs!EmployeeType_ID.Value
CurrentDb.Properties.Append prop
SetProperty:
If MsgBox("Would you like to turn on the bypass key?", vbYesNo, "Allow Bypass") = vbYes Then
CurrentDb.Properties("AllowBypassKey") = True
Else
CurrentDb.Properties("AllowBypassKey") = False
End If
End If
Me.Visible = False
DoCmd.OpenForm "frmMain"
Globals.LoggingSignOn "Logon"
End Sub
Private Sub Form_Load()
Me.txtUserName = Null
Me.txtPassword = Null
Me.txtUserName.SetFocus
End Sub
Private Sub Form_Unload(Cancel As Integer)
Globals.LoggingSignOn "Logoff"
End Sub
Private Sub Form_Load()
If Nz(DLookup("HasAccess", "tbl9EmployeeAccess", "EmployeeType_ID=" & TempVars("EmployeeType") & " FormName='" & Me.Name & "'"), False) = False Then
MsgBox "You do not have access to access this location."
DoCmd.Close acForm, Me.Name
End If
End Sub
Thank you for your time, to anybody that looks into this.
This code was running without a hitch, but now getting Error 2585.
I have looked at Gustav's answer and Gord Thompson's answer but unless I am missing something (quite possible!) the first does not work and the second seems inapplicable. I saw on another site a suggestion that there might be a duplicate record ID, but I check for that possibility.
I put a call to DoEvent() in response to this error but it returns zero. I also wait for 10 seconds to let other processes run. Still receive the error.
Private Sub SaveData_Click()
Dim myForm As Form
Dim myTextBox As TextBox
Dim myDate As Date
Dim myResponse As Integer
If IsNull(Forms!Ecoli_Data!DateCollected.Value) Then
myReponse = myResponse = MsgBox("You have not entered all the required data. You may quit data entry by hitting 'Cancel'", vbOKOnly, "No Sample Date")
Forms!Ecoli_Data.SetFocus
Forms!Ecoli_Data!Collected_By.SetFocus
GoTo endOfSub
End If
If Me.Dirty Then Me.Dirty = False
myDate = Me.DateCollected.Value
Dim yearAsString As String, monthAsString As String, dayAsString As String, clientInitial As String
Dim reportNumberText As String
reportNumberText = Me!SampleNumber.Value
Debug.Print "reportNumberText = " & reportNumberText
Debug.Print "CollectedBy Index: " & Me!Collected_By & " Employee Name: " & DLookup("CollectedBy", "Data_Lookup", Me.Collected_By)
Dim whereString As String
whereString = "SampleNumber=" & "'" & reportNumberText & "'"
Debug.Print whereString
On Error GoTo errorHandling
DoCmd.OpenReport "ECOLI_Laboratory_Report", acViewPreview, , whereString
DoCmd.PrintOut
DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo
Dim eventsOpen As Integer
eventsOpen = DoEvents()
Debug.Print "Number of Open Events = " & DoEvents()
Dim PauseTime, Start, Finish, TotalTime
PauseTime = 10 ' Set duration.
Start = Timer ' Set start time.
Do While Timer < Start + PauseTime
DoEvents ' Yield to other processes.
Loop
Finish = Timer ' Set end time.
TotalTime = Finish - Start ' Calculate total time.
myResponse = MsgBox("Processing Report Took " & TotalTime & " seconds.", vbOKOnly)
myResponse = MsgBox("Do you want to add more data?", vbYesNo, "What Next?")
If myResponse = vbYes Then
DoCmd.Close acForm, "ECOLI_Data", acSaveYes
Error Generated By Line Above and occurs whether response Y or N to MsgBox.
DoCmd.OpenForm "ECOLI_Data", acNormal, , , acFormAdd
DoCmd.GoToRecord , , acNewRec
Else
DoCmd.Close acForm, "ECOLI_Data", acSaveYes
End If
Exit Sub
errorHandling:
If Err.Number = 2501 Then
myResponse = MsgBox("Printing Job Cancelled", vbOkayOnly, "Report Not Printed")
ElseIf Err.Number = 0 Then
'Do nothing
Else
Debug.Print "Error Number: " & Err.Number & ": " & Err.Description
myResponse = MsgBox("An Error occurred: " & Err.Description, vbOKOnly, "Error #" & Err.Number)
End If
If Application.CurrentProject.AllForms("ECOLI_Data").IsLoaded Then DoCmd.Close acForm, "ECOLI_Data", acSaveNo
If Application.CurrentProject.AllReports("ECOLI_Laboratory_Report").IsLoaded Then DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo
endOfSub:
End Sub
Any idea on what am I missing here? Thanks.
I can't replicate the problem, but the following might help:
I assume you run into troubles because you're closing and opening the form in the same operation. To avoid doing this, you can open up a second copy of the form, and close the form once the second copy is open. This avoids that issue.
To open a second copy of the form:
Public Myself As Form
Public Sub CopyMe()
Dim myCopy As New Form_CopyForm
myCopy.Visible = True
Set myCopy.Myself = myCopy
End Sub
(CopyForm is the form name)
To close a form that may or may not be a form created by this function
Public Sub CloseMe()
If Myself Is Nothing Then
DoCmd.Close acForm, Me.Name
Else
Set Myself = Nothing
End If
End Sub
More information on having multiple variants of the same form open can be found here, but my approach differs from the approach suggested here, and doesn't require a second object to hold references and manage copies.
This line of code
`DoCmd.Close acForm, "ECOLI_Data", acSaveYes`
doesn't save the record you are on, it just saves any changes to the form design.
You should probably use
If Me.Dirty Then Me.dirty = False
to force a save of the current record if any data has changed.
In my database, I can made a command button import a file using the following:
DoCmd.TransferText acImportDelim, "Raw Data from Import_ Import Specification", "Raw Data from Import", D:\Users\Denise_Griffith\Documents\Griffith\PRIME RECON FILES\jdaqawmslesfilesemailDLX_SHPREC_2017-04-26_03-33-47.csv, True, ""
But I would like to have the user choose the file to import, since the filename is different every day based on date and time it was created. I have found this site (http://access.mvps.org/access/api/api0001.htm) and was able to get the dialog to pop up to allow the user to navigate and select the file, but I do not know how to incorporate it so the file selected is imported using the specification I created, and into the appropriate table.
Please help!
You need to set a reference to Microsoft Office Object Library.
Public Sub ImportDocument()
On Error GoTo ErrProc
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = "Some folder"
.Title = "Some Title"
With .Filters
.Clear
.Add "CSV documents", "*.csv", 1
End With
.ButtonName = " Import Selected "
.AllowMultiSelect = False
If .Show = 0 Then GoTo Leave
End With
Dim selectedItem As Variant
For Each selectedItem In fd.SelectedItems
DoCmd.TransferText acImportDelim, "Raw Data from Import_ Import Specification", "Raw Data from Import", selectedItem, True, ""
Next
Leave:
Set fd = Nothing
On Error GoTo 0
Exit Sub
ErrProc:
MsgBox Err.Description, vbCritical
Resume Leave
End Sub
Update after user's comments:
You must change the Sub to a Function and check the return value.
The simplest way is to return a Boolean, where FALSE indicates aborted and TRUE indicates success. However by doing so, you exclude the Error scenario as both Aborted and Error will return FALSE.
Therefore you can return a Long value e.g. 0, 1, 2 indicating Aborted, Success and Error respectively. In order to avoid the "magic numbers" though, I would create and return an Enum type as shown below:
Public Enum TaskImportEnum
Aborted = 0 'default
Success
Failure
End Enum
Public Function ImportDocument() As TaskImportEnum
On Error GoTo ErrProc
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = "Some folder"
.Title = "Dialog Title"
With .Filters
.Clear
.Add "CSV documents", "*.csv", 1
End With
.ButtonName = " Import Selected "
.AllowMultiSelect = False 'Change this to TRUE to enable multi-select
'If aborted, the Function will return the default value of Aborted
If .Show = 0 Then GoTo Leave
End With
Dim selectedItem As Variant
For Each selectedItem In fd.SelectedItems
DoCmd.TransferText acImportDelim, "Raw Data from Import_ Import Specification", "Raw Data from Import", selectedItem, True, ""
Next selectedItem
'Return Success
ImportDocument = TaskImportEnum.Success
Leave:
Set fd = Nothing
On Error GoTo 0
Exit Function
ErrProc:
MsgBox Err.Description, vbCritical
ImportDocument = TaskImportEnum.Failure 'Return Failure if error
Resume Leave
End Function
Lastly, you can call the Function like this:
Sub Import()
Dim status_ As TaskImportEnum
status_ = ImportDocument
Select Case status_
Case TaskImportEnum.Success:
MsgBox "Success!"
Case TaskImportEnum.Failure:
MsgBox "Failure..."
Case Else:
MsgBox "Aborted..."
End Select
End Sub
You can read more about the Enum type here: http://www.cpearson.com/excel/Enums.aspx
I would like to disable the bypass key of my database on the open form event during the autoexec so that the user is not able to view the underlying tables of my form. I have found the following code and creatd a module to run upon opening the form during the auto exec. The module is called SetBypass
Call SetBypass
Option Compare Database
Public Function SetByPass(rbFlag As Boolean, File_name As String) As Integer
DoCmd.Hourglass True
On Error GoTo SetByPass_Error
Dim db As Database
Set db = DBEngine(0).OpenDatabase(File_name)
db.Properties!AllowBypassKey = rbFlag
setByPass_Exit:
MsgBox "Changed the bypass key to " & rbFlag & " for database " & File_name, vbInformation, "Skyline Shared"
db.Close
Set db = Nothing
DoCmd.Hourglass False
Exit Function
SetByPass_Error:
DoCmd.Hourglass False
If Err = 3270 Then
' allowbypasskey property does not exist
db.Pro perties.Append db.CreateProperty("AllowBypassKey", dbBoolean, rbFlag)
Resume Next
Else
' some other error message
MsgBox "Unexpected error: " & Error$ & " (" & Err & ")"
Resume setByPass_Exit
End If
End Function
The above module need to be called form out side the application
try the below code if you are in same database
Sub blockBypass()
Dim db As Database, pty As DAO.Property
Set db = CurrentDb
On Error GoTo Constants_Err 'Set error handler
db.Properties("Allowbypasskey") = False
db.Close
Constants_X:
Exit Sub
Constants_Err:
If Err = 3270 Then 'Bypass property doesn't exist
'Add the bypass property to the database
Set pty = db.CreateProperty("AllowBypassKey", dbBoolean _
, APP_BYPASS)
db.Properties.Append pty
Resume Next
End If
MsgBox Err & " : " & Error, vbOKOnly + vbExclamation _
, "Error loading database settings"
End Sub
This is my first attempt to create a login form. I've read up a few forums about it and tried them myself. However, I've encountered the error when trying out the form.
"Run time error '2001': You canceled the previous operation."
Here's my code! The error highlighted is the DLOOKUP statement. When I move my cursor to LanID, it appears to be 0. (I guess it got something to do with it?)
Option Compare Database
Option Explicit
Private intLoginAttempts As Integer
Private Sub cmdLogin_Click()
'Check mandatory fields
If IsNull(Me.txtLanID) Or Me.txtLanID = "" Then
MsgBox "Lan ID is required.", vbOKOnly, "Required Data"
Me.txtLanID.SetFocus
Exit Sub
End If
If IsNull(Me.txtPassword) Or Me.txtPassword = "" Then
MsgBox "Password is required.", vbOKOnly, "Required Data"
Me.txtPassword.SetFocus
Exit Sub
End If
'Compare input password and database password
If Me.txtLanID <> "" Then
If Me.txtPassword = DLookup("Password", "tblUser", "[LanID]=" & Me.txtLanID) Then
LanID = Me.txtLanID
'Close Login Page
DoCmd.Close acForm, "frmUserLogin", acSaveNo
'Check whether user is an admin
If Me.txtAdmin = DLookup("Administrator", "tblUser", "[LanID]=" & Me.txtLanID) Then
If Me.txtAdmin = -1 Then
DoCmd.OpenForm "frmMenu"
Else
DoCmd.OpenForm "frmBack"
End If
End If
Else
MsgBox "Invalid Password. Try again.", vbOKOnly, "Invalid Entry!"
Me.txtPassword.SetFocus
End If
End If
'If user enters incorrect password 3 times
intLoginAttempts = intLoginAttempts + 1
If intLoginAttempts = 3 Then
MsgBox "You do not have access to the database. Please contact system administrator.", vbCritical, "Restricted Access!"
Application.Quit
End If
End Sub
If tblUser.LanID is text data type, enclose Me.txtLanID in quotes to avoid an error with your DLookup() expression. (You don't need .Value there because it's the default property.)
DLookup("Password", "tblUser", "[LanID]='" & Me.txtLanID & "'")
If that was not the explanation, test your DLookup() expression in the Immediate window (go there with Ctrl+g) to see whether it throws an error or what value it does return.
Note, when you test DLookup() in the Immediate window, use the current value of Me.txtLanID. For example, if Me.txtLanID contains the text "foo", test it like this ...
? DLookup("Password", "tblUser", "[LanID]='foo'")