I am trying to write a VBA code on msaccess to validate the data entries to avoid duplicates on a fault log database. It works for the stLinkCriteria which is a string datatype (short text) but not for stDCriteria which is a date data type... it keeps throwing an error "type mismatch" or "datatype mismatch" on this line
stDCriteria = "[datelogged] = #" & DateTime & "#"
The stDCriteria is showing 12:00:00am when I hover my mouse on the code
Although the data type for datelogged is Date/Time in the database...
Private Sub Form_AfterUpdate()
Dim NewTerminal As String
Dim stLinkCriteria As String
Dim DateTime As Date
Dim stDCriteria As Date
NewTerminal = Me.cboTerID.Value
DateTime = Me.txtDateLogged.Value
stLinkCriteria = "[serialptrid] = " & NewTerminal & ""
stDCriteria = "[datelogged] = #" & DateTime & "#"
If Me.SerialptrID = DLookup("[serialptrid]", "Fault_Log", stLinkCriteria) Then
If Me.DateLogged = DLookup("[datelogged]", "Fault_Log", stDCriteria) Then
MsgBox "This terminal " & NewTerminal & ", " & DateTime & ", has already been entered in this database." _
& vbCr & vbCr & "Please check terminal selected", vbInformation, "Duplicate information"
Me.Undo
End If
End If
End Sub
This code attempts to assign a string value to stDCriteria:
stDCriteria = "[datelogged] = #" & DateTime & "#"
So you must declare that variable as String instead of Date.
Dim stDCriteria As String
Also you can apply a yyyy-m-d format to your DateTime value. That format avoids confusion about whether your date is m/d/yyyy or d/m/yyyy format.
stDCriteria = "[datelogged] = #" & Format(DateTime, "yyyy-m-d") & "#"
Related
I have a table called “Test_Daily”. Actually I want to stop / prevent to enter same Date into its “Today_Date” field. Below is my Code, working fine for other fields, but when I try it on Date/Time field, gives me an Error that “Data Type miss Match”. Below is my code, anyone can help.
Code :
Private Sub btnTempCheckDup_Click()
Dim Vr_newDate As String
Dim VR_linkCriteria As String
Vr_newDate = Me.txtTempSave.Value
VR_linkCriteria = "[Today_Date] = " & "'" & Vr_newDate & "'"
If Me.txtTempSave = DLookup("[Today_Date]", "Test_Table", VR_linkCriteria) Then
MsgBox "This Date " & Vr_newDate & " Has Already Entered into the Database"
End If
End Sub
if you just want to prevent duplicate entries in the field, you can set the Properties of the field in Access to have the date field be indexed. it's not a VBA solution, but it works.
Use a correctly formatted string expression for the date:
Vr_newDate = Format(Me.txtTempSave.Value, "yyyy\/mm\/dd")
VR_linkCriteria = "[Today_Date] = #" & Vr_newDate & "#"
I'm very new to VBA so I'm not even sure if I'm heading in the right direction.
I'm using Access 2010 and I've created a form where you search for an ID and then you click to add a new record for multiple timepoints (e.g follow-up form for timepoint 1, 2, 3, 4).
I have a StudyPeriod field (long integer) where you select from a list (via query number + text). I want an error box to come if that time period has already been entered.
I've been trying to use this code but it keeps coming up with the 3464 runtime error and the de-bug highlights the If Me. line.
What am I doing wrong?
Private Sub StudyPeriod_AfterUpdate()
Dim StudyPeriod As String
Dim StLinkCriteria As String
StudyPeriod = Me.StudyPeriod.Value
StLinkCriteria = "[StudyPeriod] = " & "'" & StudyPeriod & "'"
' If line below returns error
If Me.StudyPeriod = DLookup("[StudyPeriod]", "3_Questionnaire", StLinkCriteria) Then
MsgBox "This questionnaire has already been entered for this participant." _
& vbCr & vbCr & "Please check RegID or Summary table.", vbInformation, _
"Duplicate information"
Me.Undo
End If
End Sub
Your StudyPeriod field in your 3_Questionnaire table is a numeric datatype (Long Integer). So do not include quotes before and after the value of your StudyPeriod variable when you build the StLinkCriteria string:
'StLinkCriteria = "[StudyPeriod] = " & "'" & StudyPeriod & "'"
StLinkCriteria = "[StudyPeriod] = " & StudyPeriod
If Me.StudyPeriod = DLookup("[StudyPeriod]", "3_Questionnaire", StLinkCriteria) Then
First thing's first. Here's my code.
Dim conn As ADODB.Connection
Dim rec1 As ADODB.Recordset
Dim connStr As String
Dim thisSql As String
Dim testStr As String
Sub Button3_Click()
Worksheets("Sheet5").Range("N1") = Worksheets("Sheet5").Range("N1") + 1
Set conn = New ADODB.Connection
connStr = "DSN=myDatabase;UID=myUsername;PWD=myPassword;APP=Microsoft Office 2013;WSID=myPCname;DATABASE=myDatabase"
conn.Open connStr
thisSql = "SELECT myDatabase.OrderNumber, myDatabase.CustomerName, myDatabase.ShipProd, myDatabase.Sum of Sales, myDatabase.InvoiceDate FROM myDatabaseAddress "
thisSql = thisSql & "WHERE (myDatabase.ShipProd Like '" & Worksheets("Sheet5").Range("C2") & "') "
thisSql = thisSql & "GROUP BY myDatabase.CustomerName, myDatabase.OrderNumber, myDatabase.InvoiceDate, myDatabase.ShipProd, myDatabase.OEELPrimarySlsCrdtWhse "
thisSql = thisSql & "HAVING (myDatabase.OEELPrimarySlsCrdtWhse Like 'MI%') "
thisSql = thisSql & "AND (myDatabase.InvoiceDate Between {ts '" & Worksheets("Sheet5").Range("E2") & "'} And {ts '" & Worksheets("Sheet5").Range("F2") & "'}) "
thisSql = thisSql & "ORDER BY myDatabase.CustomerName ASC"
Set rec1 = New ADODB.Recordset
rec1.Open thisSql, conn
Worksheets("Sheet5").Range("A3:F10000").Clear
With Worksheets("Sheet5").QueryTables.Add(Connection:=rec1, Destination:=Worksheets("Sheet5").Range("A3"))
.Name = "data"
.FieldNames = True
.Refresh BackgroundQuery:=False
End With
End Sub
I am trying to send a query with parameters and bring back some results from my SQL database. One of the parameters that I want to pass is a date range that InvoiceDate must fall between. These dates are located in cells E2 and F2. When I run the code, I receive an error that says
Run-time error '-2147217913 (80040e07)':
[Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting date and/or time from character string.
When I push "Debug" on the message box, it highlights the line with the code
rec1.Open thisSql, conn
I have tried formatting the cells in the spreadsheet many different ways including yyyymmdd and m/d/yyyy h:mm and mm/dd/yyyy hh:mm:ss.
Another problem that I'm running into is that one of the field names is "Sum of Sales". This section generates an error saying that "of" is a reserved keyword.
If there are any suggestions that anyone has, that would be greatly appreciated.
UPDATE
I managed to fix the date/time error by changing
thisSql = thisSql & "AND (myDatabase.InvoiceDate Between {ts '" & Worksheets("Sheet5").Range("E2") & "'} And {ts '" & Worksheets("Sheet5").Range("F2") & "'}) "
to
thisSql = thisSql & "AND (myDatabase.InvoiceDate Between '" & Worksheets("Sheet5").Range("E2") & "' And '" & Worksheets("Sheet5").Range("F2") & "') "
Although, I am still working on fixing the field name problem. I have tried putting 'myDatabase.Sum of Sales' in single quotes like it is here, but that just returns "myDatabase.Sum of Sales" in all of the cells in the corresponding column.
I am importing a CSV file into a table in MS Access.
However there are many files in the folder with the same extension and the names include dates in "mm_dd_yyyy" format.
Example: Lets say I have two CSV files:
my_music_02_10_2013_01_58_07_PM.csv
my_music_02_11_2013_03_04_07_PM.csv
Both files are in the same folder, myfolder. I want to import the file whose name contains the newest date.
Here is a short snippet of my code:
strPath = "F:\myfolder\"
strFile = Dir(strPath & "my_music" & "*.csv")
How can I determine which of my "my_music*.csv" is newest?
Seems to me the key is to extract the Date/Time from each file name so that you may compare those to find which of them is newest.
Here is an Immediate window session testing the function included below. The function returns null if it can't find a string which represents a valid date.
? DateFromFilename("my_music_02_10_2013_01_58_07_PM.csv")
2/10/2013 1:58:07 PM
? DateFromFilename("my_music_no_date_here.csv")
Null
Public Function DateFromFilename(ByVal pFileName As String) As Variant
Dim strBaseName As String
Dim strDate As String
Dim strPieces() As String
Dim varReturn As Variant
varReturn = Null
strBaseName = Split(pFileName, ".")(0)
'Debug.Print "strBaseName: " & strBaseName
strPieces = Split(strBaseName, "_")
If UBound(strPieces) = 8 Then
strDate = strPieces(4) & "-" & strPieces(2) & _
"-" & strPieces(3) & " " & strPieces(5) & ":" & _
strPieces(6) & ":" & strPieces(7) & " " & strPieces(8)
End If
'Debug.Print "strDate: " & strDate
If IsDate(strDate) Then
varReturn = CDate(strDate)
End If
DateFromFilename = varReturn
End Function
I've been looking a while now for a solution to export a query with open parameters. I need to export a Query as a Formatted Excel Spreadsheet and can't create additional Tables, Queries, Forms, or Reports to the Database being used. I use DoCmd.OutputTo as it exports a formatted query unlike DoCmd.TransferSpreadsheet however I can't seem to export the query with defined parameters. I need to include the parameters or else the user will be forced to input the start and end date three times a piece as the database for some reason asks for the startDate and endDate twice and in order to keep the excel spreadsheet and the subsequent outlook section consistant i would have to ask the user to input their previous parameters again
Sub Main()
On Error GoTo Main_Err
'Visually Display Process
DoCmd.Hourglass True
Dim fpath As String
Dim tname As String
Dim cname As String
Dim tType As AcOutputObjectType
Dim tempB As Boolean
fpath = CurrentProject.path & "\"
'tType = acOutputTable
'tname = "APPROVED SWPS FOR LOOK AHEAD & BAR CHART"
tType = acOutputQuery
tname = "ASFLA&BC Query"
cname = "Temp BPC Calendar"
Dim qdfQry As DAO.QueryDef
Dim strStart As String
Dim strEnd As String
Set qdfQry = CurrentDb().QueryDefs(tname)
'strStart = InputBox("Please enter Start date (mm/dd/yyyy)")
'strEnd = InputBox("Please enter Start date (mm/dd/yyyy)")
qdfQry.Parameters("ENTER START DATE") = FormatDateTime("6/30/12", vbShortDate) 'strEnd
qdfQry.Parameters("ENTER END DATE") = FormatDateTime("7/1/12", vbShortDate) 'strStart
tempB = Backup(fpath, qdfQry, tType)
If (Not tempB) Then
MsgBox "Excel Conversion Ended Prematurely..."
Exit Sub
End If
' tempB = sendToOutlook(qdfQry, cname)
' If (Not tempB) Then
' MsgBox "Access Conversion Ended Prematurely..."
' Exit Sub
' End If
MsgBox "Procedure Completed Successfully"
Main_Exit:
DoCmd.Hourglass False
Exit Sub
Main_Err:
DoCmd.Beep
MsgBox Error$
Resume Main_Exit
End Sub
'************************************************************************************
'*
'* Excel PORTION
'*
'************************************************************************************
Public Function Backup(path As String, db As DAO.QueryDef, Optional outputType As AcOutputObjectType) As Boolean
On Error GoTo Error_Handler
Backup = False
Dim outputFileName As String
Dim name As String
Dim tempB As Boolean
'Set Up All Name Variablesand
name = Format(Date, "MM-dd-yy") & ".xls"
'Cleans Directory of Any older files and places them in an archive
SearchDirectory path, "??-??-??.xls", name
'See If File Can Now Be Exported. If Already Exists ask to overwrite
outputFileName = path & name
tempB = OverWriteRequest(outputFileName)
If tempB Then
'Formats The Table And Exports Into A Formatted SpreadSheet
'Checks if an output type was added to the parameter if not defualt to table
If Not IsMissing(outputType) Then
DoCmd.OutputTo outputType, db.name, acFormatXLS, outputFileName, False
Else
DoCmd.OutputTo acOutputTable, db.name, acFormatXLS, outputFileName, False
End If
Else
Exit Function
End If
Backup = True
Error_Handler_Exit:
Exit Function
Error_Handler:
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
Err.number & vbCrLf & "Error Source: Main Excel Backup" & vbCrLf & "Error Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
The SQL currently given looks like similar to below with omitted fields for for clarity
PARAMETERS [ENTER START DATE] DateTime, [ENTER END DATE] DateTime;
SELECT [SWPS].STATION,
[SWPS].START_DATE,
[SWPS].END_DATE,
FROM [SWPS]
WHERE ((([SWPS].STATION)
Like ("*"))
AND (([SWPS].START_DATE)<=[ENTER END DATE])
AND (([SWPS].END_DATE)>=[ENTER START DATE])
AND (([SWPS].SWP_STATUS) In ("A","P","W","T","R")));
I suggest you change the sql of the query.
Dim qdfQry As DAO.QueryDef
Dim strStart As String
Dim strEnd As String
''You could use a query specifically for this
Set qdfQry = CurrentDb.QueryDefs(tname)
sSQL=qdfQry.SQL
NewSQL = "SELECT [SWPS].STATION, [SWPS].START_DATE, [SWPS].END_DATE, " _
& "FROM [SWPS] WHERE [SWPS].STATION Like '*' " _
& "AND [SWPS].SWP_STATUS In ('A','P','W','T','R') " _
& "AND [SWPS].START_DATE)<=#" & Format(DateStart, "yyyy/mm/dd") & "# " _
& "AND [SWPS].END_DATE)>=#" & Format(DateEnd, "yyyy/mm/dd") & "#"
qdfQry.SQL = NewSQL
''Do the excel stuff
''Reset the query
qdfQry.SQL = sSQL