I have a combo box on my form with the choice of choosing organization 10, 20, 30....
I have added ALL to the combo list box, but am having trouble implementing an all statement in VBA. Below is the case statement I have to get info from organizations 10, 20, 30. How do I get ALL to generate??
Case Is = 1
If cboOrg.ListIndex < 0 Then
Call msg("Please select your organization!")
Exit Sub
End If
sQ = sQ & " CC LIKE '" & cboOrg.Value & "*'"
ORGCC = Trim(cboOrg.Value)
I think you should only generate the WHERE/AND-clause, when value is not "ALL" (instead of your current assignment):
If (cboOrg.Value <> "ALL") Then
sQ = sQ & " AND CC LIKE '" & cboOrg.Value & "*'"
End If
To make it work without changing code before (generating AND or WHERE), you could try:
If (cboOrg.Value <> "ALL") Then
sQ = sQ & " CC LIKE '" & cboOrg.Value & "*'"
Else
sQ = sQ & " 1=1"
End If
Do you really need the LIKE (does CC only start with the value selected) or would
WHERE CC = '" & cboOrg.Value & "'" be sufficient?
Private Sub cmdGo_Click()
Dim db As Database, rs As Recordset, sQ As String
Dim oXL, oExcel As Object
Set oXL = CreateObject("Excel.Application")
fPath = "\\firework\mmcfin\123files\Edmond\Lawson Query\Log\"
myTime = Now()
myFile = Environ("UserName") & "-" & Environ("ComputerName") & "-" & Replace(Replace(Replace(Trim(myTime), "/", "-"), " ", "-"), ":", "-")
pTitle = "Lawson Queries"
Set db = CurrentDb
Select Case cboActBud.ListIndex
Case Is < 0
Call msg("Please select your query type first: Actual or Budget!")
Exit Sub
Case Is = 0
sQ = "SELECT * INTO [" & myFile & "] FROM ACT"
toAdd = "WHERE"
Case Is = 1
sQ = "SELECT * INTO [" & myFile & "] FROM BUD"
If cboBucket.ListIndex < 0 Then
Call msg("Please select your budget bucket!")
Exit Sub
Else
toAdd = "WHERE BUDGET_NBR = " & cboBucket.Value & " AND"
End If
End Select
myAcctLo = txtACCT1.Value
myAcctHi = txtACCT2.Value
If IsNull(myAcctLo) Or myAcctLo < 1000 Or myAcctLo > 99999 Then
Call msg("Account number is missing or invalid!")
Exit Sub
End If
If IsNull(myAcctHi) Then
myAcctHi = myAcctLo
End If
If myAcctLo > myAcctHi Then
Call msg("Account range is invalid!")
Exit Sub
End If
If myAcctLo < 90000 And myAcctHi >= 90000 Then
Call msg("You can query amounts or units; but, not both at the same time!")
Exit Sub
End If
Select Case myAcctLo
Case Is < 90000: sQ = sQ & "AMT " & toAdd
Case Is >= 90000: sQ = sQ & "UNT " & toAdd
End Select
Select Case cboLevel.ListIndex
Case Is < 0
Call msg("Please select your reporting level: Cost Center or Organization!")
Exit Sub
Case Is = 0
If IsNull(txtCC) Then
Call msg("Please enter your cost center!")
Exit Sub
End If
sQ = sQ & " CC = " & txtCC.Value
ORGCC = Trim(txtCC.Value)
Case Is = 1
If cboOrg.ListIndex < 0 Then
Call msg("Please select your organization!")
Exit Sub
End If
sQ = sQ & " CC LIKE '" & cboOrg.Value & "*'"
ORGCC = Trim(cboOrg.Value)
If (cboOrg.Value <> "All") Then
sQ = sQ & " CC LIKE '" & cboOrg.Value & "*'"
Else
sQ = sQ & " 1=1"
End If
End Select
If cboYear.ListIndex < 0 Then
Call msg("Please select an year!")
Exit Sub
End If
sQ = sQ & " AND FY = " & cboYear.Value & " AND (ACCT >= " & myAcctLo & " AND ACCT <= " & myAcctHi & ")"
DoCmd.Hourglass True
db.Execute sQ
sQ = "INSERT INTO tblLog (UserName, ComputerName, DateAndTime, ORGORCC, ACCT1, ACCT2, BUDGET, FY) VALUES ('" & _
Environ("UserName") & "','" & Environ("ComputerName") & "',#" & myTime & "#," & ORGCC & "," & myAcctLo & _
"," & myAcctHi & "," & IIf(cboBucket.ListIndex < 0, 0, Trim(cboBucket.Value)) & "," & Trim(cboYear.Value) & ")"
db.Execute sQ
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, myFile, fPath & myFile, True
With oXL
.Visible = True
.Workbooks.Open (fPath & myFile)
End With
Set oXL = Nothing
DoCmd.Hourglass False
db.Close
Related
I am pulling data from database into a recordset then converting to array and then writing to a CSV.
In the database all date values are stored as timestamps in this format.
2016-05-04 08:00:00.000000
But when I write to the CSV file the timestamp does not include the milliseconds.
Anyone know how to preserve the milliseconds?
Does the data in the recordset include the milliseconds?
On Error Resume Next
Dim sPassword
Dim sUserID
Dim sDefaultLib
Dim sSystem
Dim cs
Dim rc
Dim objIEDebugWindow
sDefaultLib = *library*
sUserID = *userid*
sPassword = *password*
sSystem = *system*
cs = *connectionString*
Set con = CreateObject("ADODB.Connection")
Set data = CreateObject("ADODB.Recordset")
con.Open cs, sUserID, sPassword
rc = con.State
If (rc = 1) Then
strQuery = "SELECT * FROM Library.Table FETCH FIRST 15 ROWS ONLY FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.Open strQuery, con
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Dim theYear
Dim theMonth
Dim theDay
Dim mDate
mDate = Date()
theYear = DatePart("yyyy", mDate)
theMonth = Right(String(2, "0") & DatePart("m", mDate), 2)
theDate = Right(String(2, "0") & DatePart("d", mDate), 2)
mDate = theYear & theMonth & theDate
Set csvFile = filsSysObj.OpenTextFile("C:\SampleFile_" & mDate & ".csv", 8, True)
columnCount = data.Fields.Count
Set i = 0
For Each field In data.Fields
i= i + 1
If (i <> columnCount) Then
csvFile.Write Chr(34) & field.Name & Chr(34) & ","
Else
csvFile.Write Chr(34) & field.Name & Chr(34)
End If
Next
csvFile.Write vbNewLine
End If
rowCount = data.RecordCount
row = 0
Dim row
Dim column
Dim resultsArray
Dim dateArray
resultsArray = data.GetRows
debug "hi"
i = 0
Do Until i>5
MsgBox(i)
i = i + 1
'debug "in"
'Dim value
'Dim dArray()
'debug "in"
'value = Chr(34) & CStr(data.Fields(17).Value) & Chr(34) & ","
'dArray = additem(dArray, value)
'data.MoveNext
'dateArray = dArray
Loop
debug "out"
For row = 0 To UBound(resultsArray, 2)
For column = 0 To UBound(resultsArray, 1)
If row = UBound(resultsArray, 2) And column = UBound(resultsArray, 1) Then
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34)
Else
If column = 0 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
ElseIf column = 19 Then
csvFile.Write Chr(34) & FormatDateTime(resultsArray(column, row),4) & Chr(34) & ","
ElseIf column = 18 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
'ElseIf column = 17 Then
'csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
Else
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34) & ","
End If
End If
Next
csvFile.Write vbNewLine
Next
csvFile.close
'----------------------Helper Functions are below-----------------------------
Sub Debug(myText)
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject(objIEDebugWindow) Then
Set objIEDebugWindow = CreateObject("InternetExplorer.Application")
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
Function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
End Function
The only field I am having issues with is field 17 of the recordset.
It is a timestamp datatype from a DB2 database.
The issue was the format is a timestamp in DB2 database. When i pull into a recordset it loses the milliseconds. My solution was to modify the query to add an extra row that pulls in only milliseconds and then later concatenate that back to the date. Please see below. Thanks for everyones help.
if(rc = 1) then
logFile.write FormatDateTime(Now(), 3) & ": Database connection successful" & vbNewLine
logFile.write FormatDateTime(Now(), 3) &": Default Library: " & sDefaultLib & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": Signed into server as: " & sUserID & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": System: " & sSystem & vbNewLine
strQuery = "SELECT ws_date, groupcd, userid, firstname, lastname, clientcd, unitcd, categorycd, category, activity, wrktype, subwrktype, step_begin, step_end, report_indicator, report_indicator, count, event_dattim, key_date, key_time, key_milsec, microsecond(event_dattim) FROM *Library.Name* FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.open strQuery, con
if data.EOF then
logFile.write FormatDateTime(Now(), 3) & ": The query returned no data"
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". There was no worksteps file created. ----------------" & vbNewLine
logFile.close
end if
columnCount = data.Fields.Count
columnCount = columnCount - 1
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Set csvFile = filsSysObj.OpenTextFile("C:\VBScript\Dailys\" & fname, 8, True)
set i = 0
for each field in data.Fields
i= i + 1
if i < columnCount then
csvFile.Write chr(34) & field.name & chr(34) & ","
elseif i = columnCount then
csvFile.Write chr(34) & field.name & chr(34)
else
exit for
end if
next
csvFile.Write vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": Database connection was unsuccessful. Database Connection Return Code: " & rc
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logFile.close
csvfile.close
wscript.quit
end if
dim row
dim column
dim resultsArray
resultsArray = data.GetRows
dim arrayRows
arrayRows = ubound(resultsArray, 2)
if arrayRows <> 0 then
logFile.write FormatDateTime(Now(), 3) & ": " & (arrayRows + 1) & " rows were successfully read into the array for file " & fname & vbnewline
for row = 0 to UBound(resultsArray, 2)
for column = 0 to (UBound(resultsArray, 1) - 1)
if row = Ubound(resultsArray, 2) and column = (ubound(resultsArray, 1) - 1) then
csvFile.Write chr(34) & resultsArray(column, row) & chr(34)
else
if column = 0 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 19 then
csvFile.Write chr(34) & FormatDateTime(resultsArray(column, row),4) & chr(34) & ","
elseif column = 18 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 17 then
Dim fDate
fDate = formatDate(resultsArray(column, row)) & " " & FormatDateTime(resultsArray(column, row),4) & ":" & second(resultsArray(column,row)) & "." & resultsArray((ubound(resultsArray, 1)), row)
csvFile.Write chr(34) & fDate & chr(34) & ","
else
csvFile.Write chr(34) & resultsArray(column, row) & chr(34) & ","
end if
end if
next
csvFile.Write vbNewLine
next
logfile.write FormatDateTime(Now(), 3) & ": " & (row) & " rows have been written to " & fname &vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": There was no data in the query results array for file " & fname & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logfile.close
csvfile.close
wscript.quit
end if
csvFile.close
logfile.write "---------------- DailyWorkstepReport.vbs script successfully ended at " & Now() & "----------------" & vbNewLine
logfile.close
wscript.quit
REM ----------------------Helper Functions are below-----------------------------
Sub Debug( myText )
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject( objIEDebugWindow ) Then
Set objIEDebugWindow = CreateObject( "InternetExplorer.Application" )
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
end function
Sub Main()
StartTime = Now()
TDate = CDate(Format(Now(), "MM/DD/YYYY"))
My = Environ("Username")
Set db = CurrentDb
Set rs = db.OpenRecordset("Emp", dbOpenDynaset)
Criteria = "ID = '" & My & "' And From_Date >= '" & TDate & "' And To_Date <= '" & StartTime & "' "
rs.FindFirst Criteria
If rs.NoMatch Then
MsgBox "Record not found"
else
MsgBox "Record found"
end if
Please help to run this code as I would like to find first record between start date & end date.
For a date you should use a "#" as enclosing character:
Criteria = "ID = '" & My & "' And From_Date >= #" & TDate & "# And To_Date <= #" & StartTime & "# "
You are mixing up date and time formatting:
Sub Main()
' Dim StartTime As Date
' Dim TDate As Date
StartTime = Now
TDate = DateValue(StartTime)
My = Environ("Username")
Set db = CurrentDb
Set rs = db.OpenRecordset("Emp", dbOpenDynaset)
Criteria = "ID = '" & My & "' And From_Date >= #" & Format(TDate, "yyyy\/mm\/dd") & "# And To_Date <= #" & Format(StartTime, "yyyy\/mm\/dd") & "#'"
rs.FindFirst Criteria
If rs.NoMatch Then
MsgBox "Record not found"
Else
MsgBox "Record found"
End If
End Sub
However, it could be reduced to:
Sub Main()
My = Environ("Username")
Set db = CurrentDb
Set rs = db.OpenRecordset("Emp", dbOpenDynaset)
Criteria = "ID = '" & My & "' And From_Date >= Date() And To_Date <= Now()"
rs.FindFirst Criteria
If rs.NoMatch Then
MsgBox "Record not found"
Else
MsgBox "Record found"
End If
End Sub
I have 8 combo boxes in an Access database. Each combo box can either have a value or not have a value (2 options). In total, there can be 256 combinations (2^8). I am trying to create some code in VBA that loops through these combinations to determine which combination currently exists, with the ultimate goal of writing an SQL query within VBA based on that combination. So for example, let's say combo1 and combo2 both have selections, but not combo3 through combo8. If that is the combination I would like my SQL query to do a SELECT FROM query WHERE a column in db = combo1 and a column in db = combo2. Can anyone provide hints as to how I would structure my code?
Thanks!
Dim a as string, b as string
const myAND as string = "AND "
a = ""
a = "SELECT * FROM a table "
b = ""
if cbo1.value <> "" then
b = b & myAND & "AND field1 = '" & cbo1.value & "'"
end if
if cbo2.value <> "" then
b = b & myAND & "field2 = '" & cbo2.value & "'"
end if
etc for each cbo box
If b <> "" Then
' Lazy way
' a = a & "WHERE 1=1 " & b
' remove the first AND way
a = a & "WHERE 1=1 " & mid(b,len(myAND))
End if
' a now contains the SQL you need.
Dim where_condtion as String
Dim sqlquery as String
where_condtion = ""
IF combo1 <>"" then
where_condtion = where_condtion + "~fieldname~ = " & combo1
End IF
IF combo2 <>"" then
where_condtion = where_condtion + "AND ~fieldname~ = " & combo2
End IF
*
*
*
IF combo8 <>"" then
where_condtion = where_condtion + "AND ~fieldname~ =" & combo8
End IF
IF where_condtion <> "" then
sqlquery = "Select * from ~table name~ where" + where_condtion
ELSE
sqlquery = "Select * from ~table name~
End IF
sqlquery = Replace(sqlquery, "where AND ", "where ")
DoCmd.OpenQuery "sqlquery", acViewNormal, acEdit
OR
CurrentDb.OpenRecordset("sqlquery")
Am option would be a concatenated string
Code Example
Dim strSQL as String
'basic string
strSQL = "SELECT tbl.fieldA, tbl.fieldB FROM tbl "
Dim strSQLwhere as String
strSQLwhere = ""
'Combobox cmbbox1
If Not isNull(cmbbox1) And cmbbox1.ListIndex <> -1 then
strSQLwhere = strSQLwhere & "tbl.fieldToFilter1=" & cmbbox1
End if
'Combobox cmbbox2
If Not isNull(cmbbox2) And cmbbox2.ListIndex <> -1 then
iF NOT strSQLwhere = "" then
strSQLwhere = strSQLwhere & " AND "
end if
strSQLwhere = strSQLwhere & "tbl.fieldToFilter2=" & cmbbox2
End if
'And so on until cmbBox 8
'Combine all Strings
if not strSQLwhere = "" then
strSQL = strSQL & " WHERE (" & strSQLwhere & ")"
End if
'Add here further thing like ORDER BY, GROUP BY
'Show SQL sting if it is well fomratted, change string concatenation if not
debug.print strSQL
You could do the combobox if-then-(else) cases in a separate function if you are able to do that in VBA.
I'm trying to delete all the records of one table that appear in another, however it only seems to delete some of the records.
Private Sub removeDuplicates()
Dim resultSet1 As DAO.Recordset
Set resultSet1 = CurrentDb.OpenRecordset("remove")
resultSet1.MoveFirst
Do Until resultSet1.EOF
Dim sql As String
sql = "Delete * from [Copy Of remove] Where"
If Not IsNull(resultSet1.Fields(0)) And (resultSet1.Fields(0) <> "") Then
sql = sql & " PHN = """ & resultSet1.Fields("PHN") & """"
End If
If Not IsNull(resultSet1.Fields(1)) And (resultSet1.Fields(1) <> "") Then
sql = sql & " and Year = " & resultSet1.Fields(1)
End If
If Not IsNull(resultSet1.Fields(2)) And (resultSet1.Fields(2) <> "") Then
sql = sql & " and [Date of Referral to Thoracics] = " & resultSet1.Fields(2)
End If
If Not IsNull(resultSet1.Fields(3)) And (resultSet1.Fields(3) <> "") Then
sql = sql & " and [Date of Thoracics Consult] = " & resultSet1.Fields(3)
End If
If Not IsNull(resultSet1.Fields(4)) And (resultSet1.Fields(4) <> "") Then
sql = sql & " and [Date Thoracic Surgery Booked] = " & resultSet1.Fields(4)
End If
If Not IsNull(resultSet1.Fields(5)) And (resultSet1.Fields(5) <> "") Then
sql = sql & " and [Date of Thoracic Surgery] = " & resultSet1.Fields(5)
End If
If Not IsNull(resultSet1.Fields(6)) And (resultSet1.Fields(6) <> "") Then
sql = sql & " and [Study Group] = """ & resultSet1.Fields(6) & """"
End If
If Not IsNull(resultSet1.Fields(7)) And (resultSet1.Fields(7) <> "") Then
sql = sql & " and [Access Method] = """ & resultSet1.Fields(7) & """"
End If
If Not IsNull(resultSet1.Fields(8)) And (resultSet1.Fields(8) <> "") Then
sql = sql & " and Procedure = """ & resultSet1.Fields(8) & """"
End If
If Not IsNull(resultSet1.Fields(9)) And (resultSet1.Fields(9) <> "") Then
sql = sql & " and Site = """ & resultSet1.Fields(9) & """"
End If
If Not IsNull(resultSet1.Fields(10)) And (resultSet1.Fields(10) <> "") Then
sql = sql & " and [Procedure 2] = """ & resultSet1.Fields(10) & """"
End If
If Not IsNull(resultSet1.Fields(11)) And (resultSet1.Fields(11) <> "") Then
sql = sql & " and [Site 2] = """ & resultSet1.Fields(11) & """"
End If
If Not IsNull(resultSet1.Fields(12)) And (resultSet1.Fields(12) <> "") Then
sql = sql & " and [Primary site] = """ & resultSet1.Fields(12) & """"
End If
If Not IsNull(resultSet1.Fields(13)) And (resultSet1.Fields(13) <> "") Then
sql = sql & " and Grade = """ & resultSet1.Fields(13) & """"
End If
If Not IsNull(resultSet1.Fields(14)) And (resultSet1.Fields(14) <> "") Then
sql = sql & " and [T Stage] = """ & resultSet1.Fields(14) & """"
End If
If Not IsNull(resultSet1.Fields(15)) And (resultSet1.Fields(15) <> "") Then
sql = sql & " and [N Stage] = """ & resultSet1.Fields(15) & """"
End If
If Not IsNull(resultSet1.Fields(16)) And (resultSet1.Fields(16) <> "") Then
sql = sql & " and [M Stage] = """ & resultSet1.Fields(16) & """"
End If
If Not IsNull(resultSet1.Fields(17)) And (resultSet1.Fields(17) <> "") Then
sql = sql & " and [Same Staging?] = """ & resultSet1.Fields(17) & """"
End If
CurrentDb.Execute sql
resultSet1.MoveNext
Loop
resultSet1.Close
End Sub
This is the code I'm using, to test if it works I've been using the table remove and Copy Of Remove but only about 20 of the 135 records are being deleted even though one is a copy of the other.
Also I match all fields when creating the delete query and I have a feeling this is where the issue is coming from.
P.S.
Option explicit and option compare database are declared above this sub
You haven't quoted your date value, so you're doing a division operation:
DELETE ... WHERE [Date...] = 6/5/2013
which becomes
DELETE ... WHERE [Date...] = 0.0005961etc...
Try
DELETE ... WHERE [Date...] = #6/5/2013#
^--------^
instead.
Context:
I made a Vacation tracking module in my database. The employees can request advanced hours take off in a current year period and it will be deducted from their next years period.
The Case:
I am trying to make a continuous loop through the recordset of employees to see if they have been awarded advanced hours and if yes add it to the vacation hours they have.
The Problem:
I have the logic down but I can't get it to loop through each employee on my continuous form.
With Me.RecordsetClone
While Not .EOF
adv = DLookup("advhours", "dbo_employees", "[empid] = txtempid")
vac = DLookup("vhrs", "dbo_employees", "[empid] = txtempid")
adate = DLookup("advdate", "dbo_employees", "[empid] = txtempid")
andatestart = DLookup("anndate", "dbo_employees", "[empid] = txtempid")
andateend = DateAdd("yyyy", AgeSimple([andatestart]), [andatestart])
anddateend = DateAdd("yyyy", 1, andateend)
morehours = DLookup("totalvachrs", "dbo_employees", "[empid] = txtempid")
sum = adv + vac
If adv > 0 And adate > DateAdd("yyyy", AgeSimple([andatestart]), [andatestart]) And adate < anddateend And morehours = 0 Then
morehours = 1
' sets the flag to 1 if true.
DoCmd.RunSQL "UPDATE dbo_employees " & "SET dbo_employees.totalvachrs='" & morehours & "' " & "WHERE dbo_employees.empid=" & txtempid & ";"
'increment vacation hours
DoCmd.RunSQL "UPDATE dbo_employees " & "SET dbo_employees.vhrs='" & sum & "' " & "WHERE dbo_employees.empid=" & txtempid & ";"
End If
'after Vac hours have been updated..
If morehours = 1 And adate < andateend Then
' puts vacation hours back down to where they were.
vac = vac - adv
DoCmd.RunSQL "UPDATE dbo_employees " & _
"SET dbo_employees.vhrs='" & _
vac & "' " & _
"WHERE dbo_employees.empid=" & txtempid & ";"
adv = 0
DoCmd.RunSQL "UPDATE dbo_employees " & _
"SET dbo_employees.advhours='" & _
adv & "' " & _
"WHERE dbo_employees.empid=" & txtempid & ";"
morehours = 0
DoCmd.RunSQL "UPDATE dbo_employees " & _
"SET dbo_employees.totalvachrs='" & _
morehours & "' " & _
"WHERE dbo_employees.empid=" & txtempid & ";"
End If
Debug.Print txtempid ' CTRL G to see
If Not .EOF Then .MoveNext
Wend
End With
MsgBox "after loop: " & txtempid
I have also tried this as well, but i get drop changes dialogue in access
Set rs = Me.RecordsetClone
rs.MoveFirst
Do While Not rs.EOF
Me.Bookmark = rs.Bookmark
adv = DLookup("advhours", "dbo_employees", "[empid] = txtempid")
vac = DLookup("vhrs", "dbo_employees", "[empid] = txtempid")
adate = DLookup("advdate", "dbo_employees", "[empid] = txtempid")
andatestart = DLookup("anndate", "dbo_employees", "[empid] = txtempid")
andateend = DateAdd("yyyy", AgeSimple([andatestart]), [andatestart])
anddateend = DateAdd("yyyy", 1, andateend)
morehours = DLookup("totalvachrs", "dbo_employees", "[empid] = txtempid")
sum = adv + vac
If adv > 0 And adate > DateAdd("yyyy", AgeSimple([andatestart]), [andatestart]) And adate < anddateend And morehours = 0 Then
morehours = 1
DoCmd.RunSQL "UPDATE dbo_employees " & "SET dbo_employees.totalvachrs='" & morehours & "' " & "WHERE dbo_employees.empid=" & txtempid & ";"
DoCmd.RunSQL "UPDATE dbo_employees " & "SET dbo_employees.vhrs='" & sum & "' " & "WHERE dbo_employees.empid=" & txtempid & ";"
End If
If morehours = 1 And adate < andateend Then
vac = vac - adv
DoCmd.RunSQL "UPDATE dbo_employees " & _
"SET dbo_employees.vhrs='" & _
vac & "' " & _
"WHERE dbo_employees.empid=" & txtempid & ";"
adv = 0
DoCmd.RunSQL "UPDATE dbo_employees " & _
"SET dbo_employees.advhours='" & _
adv & "' " & _
"WHERE dbo_employees.empid=" & txtempid & ";"
morehours = 0
DoCmd.RunSQL "UPDATE dbo_employees " & _
"SET dbo_employees.totalvachrs='" & _
morehours & "' " & _
"WHERE dbo_employees.empid=" & txtempid & ";"
End If
Me.Bookmark = rs.Bookmark
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
DotyDot,
I think that your problem is a basic misunderstanding of how recordsets and forms (and continuous forms) work.
Regardless of whether the form is a regular form (one record displayed at a time) or a continuous form (multiple records displayed at a time), the ability and limitations in referencing values (fields) on the form and/or use the recordset does not change.
You can't "loop" through a continuous form in code and reference the controls on the form (txtempid) and get the value from each record, as you are trying to do.
Anytime you reference a control on a form, you will only get the value for that control associated with the current record.
Looping through a recordset, even if you instantiate the recordset from the form recordsetclone, will NOT change the current record pointer on the form.
Your second code example is closest to something that will work, but still needs some work. First, when working with a recordset in code, you will most likely NOT reference the form controls, you will reference the field values directly from the recordset. I don't know your table structure, but here is an example that should get you on the right track.
I assume that this code will run on a button click, or some other event where you are wanting to evaluate all employees.
Dim rst as DAO.Recordset
Set rst = Me.RecordsetClone
Do While Not rst.EOF
adv = DLookup("advhours", "dbo_employees", "[empid] = " & rst("empid"))
vac = DLookup("vhrs", "dbo_employees", "[empid] = " & rst("empid"))
adate = DLookup("advdate", "dbo_employees", "[empid] = " & rst("empid"))
andatestart = DLookup("anndate", "dbo_employees", "[empid] = " & rst("empid"))
andateend = DateAdd("yyyy", AgeSimple(rst("andatestart")), rst("andatestart"))
anddateend = DateAdd("yyyy", 1, rst("andateend"))
morehours = DLookup("totalvachrs", "dbo_employees", "[empid] = " & rst("empid"))
sum = adv + vac
If adv > 0 And adate > DateAdd("yyyy", AgeSimple(rst("andatestart")), rst("andatestart")) And adate < anddateend And morehours = 0 Then
morehours = 1
rst.Edit
rst("totalvachrs") = morehours
rst("vhrs") = sum
rst.Update
End If
If morehours = 1 And adate < andateend Then
vac = vac - adv
rst.Edit
rst("vhrs") = vac
adv = 0
rst("advhours") = adv
morehours = 0
rst("totalvachrs") = morehours
rst.Update
End If
rst.MoveNext
Loop
Set rst = Nothing
'Refresh the screen
Me.Requery
You don't need to use DoCmd.RunSQL, you can edit the data directly in the Recordset via code.
Please note that in your example code, anyplace where you appeared to be referencing a control on the form
[andatestart]
I changed it to reference that field name in the recordset
rst("andatestart")
This code will loop through every record on your form and perform the calculations and updates you were doing.
FYI, in your original code, by setting the form bookmark (Me.Bookmark)
to the recordset Bookmark, you were forcing the form to move the
current record pointer through each record, but that is really not the
best way to accomplish what you are trying to do, IMO
I hope this helps.