Execute Sub after a certian amount of time? - ms-access

I am trying to execute a Sub after a certain time period after a UserForm has open. The UserForm opens immediately when Access has started. Is there an alternative to Application.OnTime? As it does not work with Access and only seems to work with Excel.
This is what I'm working with.
Private Sub UserForm_Activate()
Set objWSHShell = CreateObject("WScript.Shell")
DesktopDir = objWSHShell.SpecialFolders("Desktop") & "\"
InstallDir = Left(DesktopDir, 3) & "VICI"
VICIMxDir = InstallDir & "\VICI Mx.txt"
VICIFmDir = InstallDir & "\VICI Fm.txt"
VICIAnalyticsDir = InstallDir & "\VICI Analytics.txt"
With ListBox_Status
If FSO.FileExists(VICIMxDir) = True Then 'Both exist
.Column(1, 0) = "Ready"
Else
.Column(1, 0) = "Not Found"
End If
If FSO.FileExists(VICIFmDir) = True Then
.Column(1, 1) = "Ready"
Else
.Column(1, 1) = "Not Found"
End If
If FSO.FileExists(VICIAnalyticsDir) = True Then
.Column(1, 2) = "Ready"
Else
.Column(1, 2) = "Not Found"
End If
.Column(1, 3) = Environ("UserName")
End With
Application.OnTime Now + TimeValue("00:00:10"), "DB_BackUP"
Application.OnTime Now + TimeValue("00:00:20"), "RmvDBBackup"
End Sub

You can use Application.Wait:
Private Sub UserForm_Activate()
waitTime (3000) ' 3 seconds
MyDeleyedMethod
End Sub
Function waitTime(ByVal millsec As Double)
Application.Wait (Now() + millsec / 24 / 60 / 60 / 1000)
End Function
Private Sub MydelayedMethod()
MsgBox ("hello")
End Sub
Another way to achieve that result is:
Private Sub UserForm_Activate()
Wait (3) ' 3 seconds
MyDeleyedMethod
End Sub
Sub Wait(seconds As Integer)
Dim now As Long
now = Timer()
Do
DoEvents
Loop While (Timer < now + seconds)
End Sub
Private Sub MyDeleyedMethod()
MsgBox ("hello")
End Sub

Related

Access: Disable comboboxes

I've got 5 comboboxes in my form, and I would like the user to only be able to select 2. Once 2 is selected, the other 3 will be disabled? How'd I go about this? I know you can do one combobox and disable the rest by afterupdate as below. Appreciate your help! :)
Private Sub cboOR_AfterUpdate()
Me.cboA.Enabled = False
End Sub
Check this out
Private Sub Combo0_AfterUpdate()
If CheckCombo Then
disableCombo
Else
enableCombo
End If
End Sub
Private Sub Combo10_AfterUpdate()
If CheckCombo Then
disableCombo
Else
enableCombo
End If
End Sub
Private Sub Combo12_AfterUpdate()
If CheckCombo Then
disableCombo
Else
enableCombo
End If
End Sub
Private Sub Combo14_AfterUpdate()
If CheckCombo Then
disableCombo
Else
enableCombo
End If
End Sub
Private Sub Combo16_AfterUpdate()
If CheckCombo Then
disableCombo
Else
enableCombo
End If
End Sub
Private Function CheckCombo() As Boolean
Dim retVal As Long
retVal = IIf(Len(Nz(Combo0, "")) > 0, 1, 0) + IIf(Len(Nz(Combo10, "")) > 0, 1, 0) + IIf(Len(Nz(Combo12, "")) > 0, 1, 0) + IIf(Len(Nz(Combo14, "")) > 0, 1, 0) + IIf(Len(Nz(Combo16, "")) > 0, 1, 0)
CheckCombo = (retVal >= 2)
End Function
Private Sub enableCombo()
Combo0.Enabled = True
Combo10.Enabled = True
Combo12.Enabled = True
Combo14.Enabled = True
Combo16.Enabled = True
End Sub
Private Sub disableCombo()
If Len(Nz(Combo0, "")) <= 0 Then Combo0.Enabled = False
If Len(Nz(Combo10, "")) <= 0 Then Combo10.Enabled = False
If Len(Nz(Combo12, "")) <= 0 Then Combo12.Enabled = False
If Len(Nz(Combo14, "")) <= 0 Then Combo14.Enabled = False
If Len(Nz(Combo16, "")) <= 0 Then Combo16.Enabled = False
End Sub
Put this Sub in form's module
Private Sub changeStateOfCB()
Dim nameChB() As String
Dim cMax As Long
Dim ctrl As Control
Dim cValued As Long
Dim nameCurr As Variant
' names of CB
nameChB = Split("ComboName1#ComboName2#ComboName3#ComboName4#ComboName5", "#")
' max allowed values
cMax = 2
' counting with values
For Each nameCurr In nameChB
If Not Me.Controls(nameCurr).Value Is Null Then
cValued = cValued + 1
End If
Next
' disabling if needed
For Each nameCurr In nameChB
If Not Me.Controls(nameCurr).Value Is Null Then
Me.Controls(nameCurr).Enabled = (cValued < cMax)
End If
Next
End Sub
Change names in string according to you names in nameChB line.
And for every combo box create AfterUpdate event procedures with call
changeStateOfCB

Change Record on a Single form In Access 2016

I have a form that allows the user to select the date at the top. As the user changes the date, it should change the record to reflect. If there is a record for that date already then switch to that record, but if no record for that date create a new one. The table is set to not allow duplicates on the date column. Here is the code I have on the Form_Load event and the respective subs that I call:
Private Sub Form_Load()
Me.cobYear.Value = Year(Date)
Me.cobMonth.Value = Month(Date)
DaysChange Me
Me.cobDate.Value = Day(Date)
UpdateDate Me
DoCmd.Maximize
End Sub
Sub DaysChange(objForm As Form)
Dim i As Integer
Dim DaysInMonth As Integer
Dim LeapDay As Integer
LeapDay = 0
If (Int(objForm.cobYear / 400) = (objForm.cobYear / 400)) Or ((Int(objForm.cobYear / 4) = (objForm.cobYear / 4)) And Not (Int(objForm.cobYear / 100) = (objForm.cobYear / 100))) Then
LeapDay = IIf(objForm.cobMonth = 2, 1, 0)
End If
DaysInMonth = DLookup("DaysInMonth", "tblMonths", "MonthNumber =" & objForm.cobMonth) + LeapDay
For i = 1 To DaysInMonth
objForm.cobDate.AddItem Item:=i
Next i
End Sub
Sub UpdateDate(objForm As Form)
If Not objForm.cobDate = "" And Not objForm.cobMonth = "" And Not objForm.cobYear = "" Then
objForm.tbDate.Value = DateSerial(objForm.cobYear, objForm.cobMonth, objForm.cobDate)
DayOfWeek = Weekday(objForm.tbDate.Value, 2)
'Me!subfrmDispatchSheet.Form.cobRouteID.Requery
objForm.lblDayOfWeek.Caption = WeekdayName(Weekday(objForm.tbDate.Value))
DateOfRecord = objForm.tbDate.Value
End If
End Sub
And this is the code for when a user changes the date:
Private Sub cobDate_Change()
UpdateDate Me
ChangeRecord
End Sub
Private Sub cobMonth_Change()
DaysChange Me
UpdateDate Me
ChangeRecord
End Sub
Private Sub cobYear_Change()
DaysChange Me
UpdateDate Me
ChangeRecord
End Sub
I have tried a few ways to do this.
1) I tried completely in code:
Private Sub ChangeRecord()
If DCount("ShiftDate", "tblShiftRecap", "ShiftDate =" & Me.tbDate.Value) = 0 Then
Else
Me.tbShiftID.Value = DLookup("ShiftID", "tblShiftRecap", "ShiftDate =" & Me.tbDate.Value)
End If
Me.Requery
End Sub
How can I do this on a single form? I know how to do it if I add a subform but not if all the fields are in my single form.
Unfortunately, this tries to add a new record when I load up the form.
2) I tried doing it in the query also
SELECT tblShiftRecap.ShiftID, tblShiftRecap.MQFStartTime
FROM tblShiftRecap
WHERE (((tblShiftRecap.ShiftDate)=GetDateOfRecord()));
and the functiont that the SQL calls:
Public Function GetDateOfRecord()
GetDateOfRecord = DateOfRecord
End Function
If I get your question correctly, you want to navigate to a certain record in the current form based on a condition
To navigate the form, the easiest way is to open up a recordset clone, use .FindFirst, and then change the current record on the form to the found record:
Dim rs As Recordset
Set rs = Me.RecordsetClone 'Load form records into recordset clone
rs.FindFirst "ShiftDate = " & Format(DateOfRecord, "\#yyyy-mm-dd\#") 'Navigate to date
If Not rs.NoMatch 'If there's a matching record
Me.Bookmark = rs.Bookmark 'Navigate to it
End If

Error when trying to compile

I'm getting a compile error:
Sub or function not defined(error area in bold)
Option Compare Database
Option Explicit
Private Sub cboDates_AfterUpdate()
On Error Resume Next
Dim strInterval As String
Dim dblValue As Double
Dim datStartDate As Date
Dim datEndDate As Date
Dim WeekdayStsrt As Integer
WeekdayStsrt = 1 'Start day of week - 1=Sunday, 2=Monday, 3=Tuesday...
'Sets Start and End Date textboxes based on combobox selection
strInterval = Me.cboDates.Column(1)
dblValue = Me.cboDates.Column(2)
Select Case strInterval
Case "d"
datStartDate = Date
datEndDate = Date
Case "ww"
datStartDate = Date - Weekday(Date) + WeekdayStsrt
datEndDate = datStartDate + 6
Case "m"
datStartDate = DateSerial(Year(Date), Month(Date) + dblValue, 1)
datEndDate = DateSerial(Year(Date), Month(Date) + dblValue + 1, 0)
dblValue = 0
Case "yyyy"
datStartDate = DateSerial(Year(Date), 1, 1)
datEndDate = DateSerial(Year(Date), 12, 31)
Case "YTD"
datStartDate = DateSerial(Year(Date), 1, 1)
datEndDate = Date
strInterval = "yyyy"
Case "All"
datStartDate = DateSerial(2000, 1, 1) 'Earliest Date of available data in system
datEndDate = DateSerial(Year(Date), 12, 31)
strInterval = "d"
End Select
Me.txtStartDate = DateAdd(strInterval, dblValue, datStartDate)
Me.txtEndDate = DateAdd(strInterval, dblValue, datEndDate)
End Sub
Private Sub cboReportGroup_AfterUpdate()
On Error GoTo Err_Trap
'Filter listbox based on Report Group combobox selection.
Dim SQL As String
Me.lstReport = Null
SQL = Me.lstReport.Tag
If Not Me.cboReportGroup = "(All)" Then
SQL = SQL & " WHERE ReportGroup='" & Me.cboReportGroup & "'"
End If
SQL = SQL & " ORDER BY tsysReports.ReportTitle;"
Me.lstReport.RowSource = SQL
Err_Trap_Exit:
Exit Sub
Err_Trap:
MsgBox Err.Description
Resume Err_Trap_Exit
End Sub
Private Sub cmdEndDate_Click()
On Error Resume Next
'Launch Calendar Control
DateCheck_MEI Me.txtEndDate
Me.cboDates = Null
End Sub
Private Sub cmdExport_Click()
On Error GoTo Err_Trap
Dim SQL As String
Echo False
Call cmdOpen_Click 'execute the button that opens the report for print preview
SQLEdit_MEI "ArrivalTimingTableQuery", Application.Reports(Me.lstReport).RecordSource
If Application.Reports(Me.lstReport).Filter = "" Then
SQL = "SELECT * FROM ArrivalTimingTableQuery "
Else
SQL = "SELECT * FROM ArrivalTimingTableQuery WHERE " & Application.Reports(Me.lstReport).Filter
End If
SQLEdit_MEI "qryTempExport", SQL
DoCmd.OutputTo acOutputQuery, "qryTempExport", acFormatXLS, CurrentProject.Path & "\temp.xls", True
DoCmd.Close acReport, Me.lstReport, acSaveNo
Echo True
Err_Trap_Exit:
Exit Sub
Err_Trap:
Echo True
MsgBox Err.Description
Resume Err_Trap_Exit
End Sub
Private Sub cmdOpen_Click()
On Error GoTo Err_Trap
Dim strCriteria As String
If Me.txtEndDate < Me.txtStartDate Then
MsgBox "End Date cannot be prior to Start Date."
Exit Sub
End If
If IsNull(Me.lstReport) Then
MsgBox "Please select a report"
Exit Sub
End If
If Not Me.lstReport.Column(2) = "" Then
strCriteria = Me.cboField & " Between #" & Me.txtStartDate & "# And #" & Me.txtEndDate & "#"
End If
DoCmd.OpenReport Me.lstReport, acViewReport, , strCriteria
Err_Trap_Exit:
Exit Sub
Err_Trap:
MsgBox Err.Description
Resume Err_Trap_Exit
End Sub
Private Sub cmdStartDate_Click()
On Error Resume Next
'Launch Calendar Control
DateCheck_MEI Me.txtStartDate
Me.cboDates = Null
End Sub
Private Sub Form_Load()
Call cboReportGroup_AfterUpdate
End Sub
Private Sub lstReport_Click()
On Error Resume Next
Me.lblDescription.Caption = "Report Description: " & Me.lstReport.Column(3)
Me.cboField.RowSource = Me.lstReport.Column(2) 'Set to values of DateCriteria field of table tsysReports
Me.cboField = Me.cboField.ItemData(0) 'Select 1st item in combobox
'Hide Report Criteria Section if no Date Filter for selected report
If Me.lstReport.Column(2) = "" Then
Me.box1.Visible = True
Else
Me.box1.Visible = False
End If
End Sub
Private Sub lstReport_DblClick(Cancel As Integer)
Call cmdOpen_Click
End Sub
From what you've posted, and ignoring what may be wrong inside of your sub,
the fix would be to end the sub:
Private Sub cmdStartDate_Click()
'Do stuff
End Sub 'This is the part you are missing

On-click event on an unbound control in MS Access

I am trying to modify a sample by Roggers here for my project to browse multiple images in MS Access form.
But, I would like to know how I can add an on-click event for the image control to open a details form.
The code behind the form is as follows:
Private Sub P_FillControls()
On Error GoTo ErrTrap
Dim Cnt As Long
Cnt = 1
Do Until (Cnt > BlockSize Or rst.EOF)
P_SetValues Cnt
Cnt = Cnt + 1
rst.MoveNext
Loop
If Cnt <= BlockSize Then
For Cnt = Cnt To BlockSize
P_SetNulls Cnt
Next
End If
ExitPoint:
On Error GoTo 0
Exit Sub
ErrTrap:
MsgBox Err.Number & " - " & Err.Description
Resume ExitPoint
End Sub
Private Sub P_SetValues(Cnt As Long)
On Error GoTo ErrTrap
If RecCount > 0 Then
Me("Rn_" & Format(Cnt, "00")).Caption = (rst.AbsolutePosition + 1)
Else
Me("Rn_" & Format(Cnt, "00")).Caption = ""
End If
Me("Lb_" & Format(Cnt, "00")).Caption = Nz(rst.Fields("ImageName"), "")
Me("Im_" & Format(Cnt, "00")).Picture = Nz(rst.Fields("ImageFile"), "")
Me("ID_" & Format(Cnt, "00")) = rst.Fields("ImageFile")
' Note - For no caption, dot is used in lieu of
' zero length string, so as to prevent the
' label from disappearing
ExitPoint:
On Error GoTo 0
Exit Sub
ErrTrap:
MsgBox Err.Number & " - " & Err.Description
Resume ExitPoint
End Sub
Private Sub P_SetNulls(Cnt As Long)
On Error GoTo ErrTrap
Me("Rn_" & Format(Cnt, "00")).Caption = "."
Me("Lb_" & Format(Cnt, "00")).Caption = "."
Me("Im_" & Format(Cnt, "00")).Picture = "."
Me("ID_" & Format(Cnt, "00")) = Null
' Note - For no caption, dot is used in lieu of
' zero length string, so as to prevent the
' label from disappearing
ExitPoint:
On Error GoTo 0
Exit Sub
ErrTrap:
MsgBox Err.Number & " - " & Err.Description
Resume ExitPoint
End Sub
Public Sub P_Initialize()
On Error Resume Next
RecCount = 0 ' Default
Me.LbNoImage.Visible = False
' Remove any existing instance of the recordset
If Not rst Is Nothing Then
rst.Close
Set rst = Nothing
End If
' This recordset will finally get closed in form's
' close event.
Set rst = CurrentDb.OpenRecordset("Q_ImageNormalSort")
' Set rst = CurrentDb.OpenRecordset("Q_Dynamic_Query")
If rst.EOF And rst.BOF Then
' There are no records
P_FillControls
Me.LbNoImage.Visible = True
P_SetStatusNavBtns
Me.CmdAdd.SetFocus
Exit Sub
End If
rst.MoveLast
RecCount = rst.RecordCount
LastID = rst.Fields("ImageFile")
rst.MoveFirst
FirstID = rst.Fields("ImageFile")
' First Load (signified by step size argument = 0)
P_Next 0
Me.LbRecMsg.Caption = "Of " & RecCount
On Error GoTo 0
End Sub
In the sample, "Im_" is the control that holds the image on the form.
I will appreciate your help.
Joseph
Put the following Sub in your code somewhere at the bottom:
Function OpenMyForm(strFormName As String)
DoCmd.OpenForm strFormName
End Function
Stick this in your code below where you set the image:
Me("Im_" & Format(Cnt, "00")).OnClick = "=OpenMyForm('F_Details')"

vb 6.0 can anyone help me with my code?

Im working with my project inventory system i want to display the filtered dates in my books table in the mysql in my listview1 using 2 DTPicker and make a report for it. Im having an error in my query in the classmodule idk if its only the query and im really confused im a begginer in vb 6.0...please in need your help guys.
Im using 2 tables namely books and supplier.
MY CODE IN THE 'CLASS MODULE':
Sub DisplayList(ListView1 As ListView, DateFrom As Date, DateTo As Date)
Dim lstItem As ListItem, a As Integer
Dim rs As New ADODB.Recordset
Dim sql As String
If rs.State = adStateOpen Then rs.Close
sql = " SELECT supplier.category,books.title,books.dataAcquired,books.amount,books.quantity,books.accesionno,books.conditions" & _
" From supplier INNER JOIN books" & _
" ON supplier.code=books.code" & _
" WHERE (((books.dataAcquired)>=#" & DateFrom & "#) and ((books.dataAcquired) <=#" & DateTo & "#))" & _
" GROUP BY supplier.category,books.title,books.dataAcquired,books.amount,books.quantity,books.accesionno,books.conditions" & _
" ORDER BY books.dataAcquired DESC;"
rs.Open sql, cnn
ListView1.ListItems.Clear
Do While Not rs.EOF
a = a + 1
Set lstItem = ListView1.ListItems.Add(, , a, 1, 1)
lstItem.SubItems(1) = rs(0).Value
lstItem.SubItems(2) = rs(1).Value
lstItem.SubItems(3) = rs(2).Value
lstItem.SubItems(4) = rs(3).Value
lstItem.SubItems(5) = rs(4).Value
lstItem.SubItems(6) = rs(5).Value
lstItem.SubItems(7) = rs(6).Value
rs.MoveNext
Loop
End Sub
MY CODE IN MY FORM:
Private Sub Show_Click()
clsData.DisplayList ListView1, DTPicker1.Value, DTPicker2.Value
lblCount.Caption = ListView1.ListItems.Count
End Sub
Private Sub Form_Load()
DTPicker1.Value = Date
DTPicker2.Value = Date
End Sub
Private Sub Form_Activate()
clsData.DisplayList ListView1, DTPicker1.Value, DTPicker2.Value
lblCount.Caption = ListView1.ListItems.Count
End Sub
Change # by '
format date how yyyy-MM-dd or yyyyMMdd
sql = " SELECT supplier.category,books.title,books.dataAcquired,books.amount,books.quantity,books.accesionno,books.conditions" & _
" From supplier INNER JOIN books" & _
" ON supplier.code=books.code" & _
" WHERE (((books.dataAcquired)>='" & format(DateFrom,"yyyy-MM-dd") & "') and ((books.dataAcquired) <='" & format(DateTo,"yyyy-MM-dd") & "'))" & _
" GROUP BY supplier.category,books.title,books.dataAcquired,books.amount,books.quantity,books.accesionno,books.conditions" & _
" ORDER BY books.dataAcquired DESC;"
change loop while added validations for recordset emptys, some how
if RecordsetIsClosed(rs) then exit sub
While Not RecordSetIsEmpty(rs)
a = a + 1
Set lstItem = ListView1.ListItems.Add(, , a, 1, 1)
lstItem.SubItems(1) = rs(0).Value
lstItem.SubItems(2) = rs(1).Value
lstItem.SubItems(3) = rs(2).Value
lstItem.SubItems(4) = rs(3).Value
lstItem.SubItems(5) = rs(4).Value
lstItem.SubItems(6) = rs(5).Value
lstItem.SubItems(7) = rs(6).Value
rs.MoveNext
wend
Public Function RecordSetIsEmpty(ByRef rs As ADODB.Recordset) As Boolean
' On Local Error GoTo RecordSetIsEmpty_Error
' RecordSetIsEmpty = True
' If rs Is Nothing Then
' RecordSetIsEmpty = True
' Exit Function
' End If
' If RecordsetIsClosed(rs) = True Then
' RecordSetIsEmpty = True
' Exit Function
' End If
RecordSetIsEmpty = (rs.BOF = True And rs.EOF = True)
' RecordSetIsEmpty_Done:
' Exit Function
' RecordSetIsEmpty_Error:
' Resume RecordSetIsEmpty_Done
End Function
Public Function RecordsetIsClosed(ByRef rs As ADODB.Recordset) As Boolean
On Local Error GoTo RecordsetIsClosed_Error
RecordsetIsClosed = True
If rs Is Nothing Then
RecordsetIsClosed = True
End If
If rs.State <> adStateClosed Then
RecordsetIsClosed = False
End If
RecordsetIsClosed_Done:
Exit Function
RecordsetIsClosed_Error:
Resume RecordsetIsClosed_Done
End Function
Dont forget to open the database connection
updated thanks Mark Bertenshaw
RecordSetIsEmpty is use for problems when do movenext.. well i remember
RecordsetIsClosed is use because in some cases and databases managers return not recordset or the recordset is not correct initialized
for example access is necessary use movefist before do movenext or read values