Access date VBA else if statement only showing one - vba

I have a form where i retrieve the start date and ending date from a table in access.
The start date and end date are both known as startdate and endate.
Then i have another column which is status.
My code is like this:
sd = Me.startdate
ed = Me.enddate
DateValue (sd)
DateValue (ed)
If IsNull(sd And ed) Or (ed > Date) Then
Me.Text59 = "In use"
ElseIf (ed < Date) Then
Me.Text59 = "Free"
so basically what i wanted to do is, if the end date is earlier than today, the status will display it as Free. However, if the end date is later than today, the status will be in use. columns where the start date and end date are empty will be displayed as in use too.
My table's start date and end date are in date/time data type.
When the code runs, they only display "In use" when clearly some of my dates end earlier than today! Help please ):

You are not telling if either startdate or enddate can be Null while the other is not, so both will either be Null or hold a value. Further, startdate seems to always be earlier than enddate, thus of no importance.
Then:
Dim sd As Variant
Dim ed As Variant
Dim inuse As Boolean
sd = Me!startdate
ed = Me!enddate
If IsNull(sd) And IsNull(ed) Then
inuse = True
ElseIf DateDiff("d", Date, ed) > 0 Then
inuse = True
End If
If inuse = True Then
Me!Text59 = "In use"
Else
Me!Text59 = "Free"
End If
For a single-line code to use as ControlSource for Text59 (Nz is only used to avoid an error if ed is Null):
=IIf(IsNull([startdate]+[enddate]),"In use",IIf(DateDiff("d",Date(),Nz(ed, Date()))>0,"In use","Free"))

Related

DB2 SQL Query to group by week

I am writing an ASP.NET web form page using VB.Net. I am writing code to use on a line graph, but I can't seem to get my query to group by week. Here is my query:
SELECT F42119LA.SDMCU || '-' || F42119LA.SDLNTY AS BranchCode,
AVG(F42119la.SDIVD-F42119LA.SDDRQJ) AS Days,
WEEK(SDTRDJ) AS Day
FROM KAI400.KAIPRDDTA.EXCHBYDATE EXCHBYDATE,
KAI400.KAIPRDDTA.F42119L14 F42119LA
WHERE F42119LA.SDBCRC = EXCHBYDATE.CXCRCD
AND EXCHBYDATE.EXCHDATE = F42119LA.SDTRDJ
AND F42119LA.SDTRDJ>='118006'
AND F42119LA.SDTRDJ<='118096'
AND F42119LA.SDNXTR<>'999'
AND SDIVD <> 0
AND SDDRQJ <> 0
AND F42119LA.SDAEXP <> 0
AND EXCHBYDATE.CXCRDC='USD'
AND F42119LA.SDLNTY IN ('S','W')
AND (SDMCU LIKE '%100' OR SDMCU LIKE '%150')
GROUP BY SDMCU,
SDLNTY,
SDIVD,
F42119LA.SDMCU || '-' || F42119LA.SDLNTY,
WEEK(SDTRDJ)
ORDER BY SDIVD,
SDMCU,
SDLNTY
and this is the code the sql string runs through:
Public Shared Function GetMyDataTableString(SqlString As String, Optional IncDb As Integer = 0) As DataTable
Dim MyConn As OleDbConnection = GetMyConn(IncDb)
Dim DbCmd As New OleDbCommand(SqlString, MyConn)
Dim ReturnDataTable As New DataTable
Try
If Not MyConn.State = ConnectionState.Open Then
MyConn.Open()
End If
Dim Reader As OleDbDataReader = DbCmd.ExecuteReader(CommandBehavior.CloseConnection)
Using Reader
ReturnDataTable.Load(Reader)
End Using
Catch ex As Exception
LogSqlErrors(SqlString, "GetMyDataTableString " & ex.Message.ToString(), IncDb)
If HttpContext.Current.Session("SITEADMIN") = "True" Then
HttpContext.Current.Response.Write("<b>OleFun.GetMyDataTableString, datatable failed</b>---<br />" & ex.ToString)
End If
Finally 'Happens regardless of failing or succeeding
MyConn.Close()
End Try
Return ReturnDataTable
End Function
Whenever I use WEEK(), it gives me this error:
Value in date, time, or timestamp string not valid
ONDATE is a date field in format MM/DD/YYYY. Does anyone know another way to group by week or what might can be giving me this error? Thanks in advance for your responses.
-- date part takes the part of the date as first paramater:
-- you have:
DATEPART(SDTRDJ, wk)
-- needs to be:
DATEPART(wk, SDTRDJ)
DATEPART() might be a function in SQL Server, but it not a function in Db2. You could use WEEK() or WEEK_ISO() which are Db2 functions. https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0005481.html
You could also use EXTRACT if you are on a recent version of Db2 LUW
https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0053629.html
db2 "values extract(WEEK FROM current date)"
1
-----------
14
1 record(s) selected.
BTW you don't need to group by the concatenation of F42119LA.SDMCU || '-' || F42119LA.SDLNTY, you can group by those columns individually, and only concat in the SELECT.
In DB2, you can group days in same week using following methods:
DATE_PART('WEEK', dateColumn) -> week starts at Saturday
WEEK(dateColumn) -> week starts at Sunday
WEEK_ISO(dateColumn) -> week starts at Monday
DAYS(dateColumn) / 7 -> week starts at Sunday
Notes:
I believe that they work with columns of type DATE as will as TIMESTAMP.
"DAYS(dateColumn) / 7" doesn't get you week number, however it is helpful in grouping by week.
Kindly check your week start day as they differ in their results as following:

How to sum field in lightswitch app

Hi I am trying to create a small app for recording lieu time.
The code below does not return a total value for the users lieu time.
2 tables
lieu
Lieudate date.
lieuAdd boolean choice list True, False.
LieuHours decimal.
lieuTotal decimal computed field.
Users
UserName string.
LastName string.
Firstname String.
Phone Phone.
Email emailaddress.
one(users) to many(lieu)
I want to show the total amount of lieu time a person has in the lieutotal field
a running total so when a user looks at their last record it shows the last transaction and how much lieu time they have.
code for computed field
Namespace LightSwitchApplication
Public Class Lieu
Private Sub LieuTotal_Compute(ByRef result As Decimal)
' Set result to the desired field value
Dim Total As Decimal
If LieuAdd = True Then
If LieuTotal = 0 Then
Total = LieuHours
Else
Total = LieuTotal + LieuHours
result = total
End If
Else
Total = LieuTotal - LieuHours
End If
End Sub
End Class
End Namespace
Since you are computing a total, you need to use a For Each loop. Assuming the name of the table is Lieus, your code should be something like:
Private Sub LieuTotal_Compute(ByRef result As Decimal)
' Set result to the desired field value
'
For Each Lieu In Lieus
If Lieu.LieuAdd = True Then
result = result + Lieu.LieuHours
Else
result = result - Lieu.LieuHours
End If
Next
End Sub
Hope this helps

How to get records between two dates in vb.net?

All ...
I need to display records that are between the two dates passed in from DateTimePickers.
I am getting records that are NOT in between the dates that I specified from vb.net.
Please go through the code shown below....
Following is the code :
Private Sub btn_Show_Inquiry_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Show_Inquiry.Click
report_viewer_form.Report_viewer_CrystalReportViewer1.ReportSource = Nothing
report_viewer_form.Report_viewer_CrystalReportViewer1.Refresh()
str1 = "SELECT * FROM Inquiry_Details WHERE Inquiry_Date>=#" & dtp_inq_from.Text & "# AND Inquiry_Date<=#" & dtp_inq_to.Text & "#"
If dtp_inq_from.Text > dtp_inq_to.Text Then
MessageBox.Show("FROM_DATE Must Be Less Then TO_DATE.", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Exit Sub
End If
If cn.State <> ConnectionState.Open Then
cn.Open()
End If
da = New OleDbDataAdapter(str1, cn)
report_dataset = New DataSet
da.Fill(report_dataset, "table2")
If MsgBox("Do You Want to Print Report ?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
report_viewer_form.Show()
Dim cr As New ReportDocument
cr = New Inquiry_CrystalReport
cr.SetDataSource(report_dataset.Tables("table2"))
report_viewer_form.Report_viewer_CrystalReportViewer1.ReportSource = cr
End If
End Sub
Your problem seems to be in the way you parse passed date parameters to the query and they're probably not in format that Access would recognize as a valid Date type. Try with CDate() function to let Access parse your input values to its internal date type properly. It will accept any valid date expression:
Any expression that can be interpreted as a date, including date
literals, numbers that look like dates, strings that look like dates,
and dates returned from functions. A date expression is limited to
numbers or strings, in any combination, that can represent a date from
January 1, 100 – December 31, 9999.
Your code could thus look like this:
str1 = "SELECT * FROM Inquiry_Details WHERE Inquiry_Date>=CDate('" &
dtp_inq_from.Text & "') AND Inquiry_Date<=CDate('" &
dtp_inq_to.Text & "')"
Another function that you might want to try (if CDate won't cut it) is DateValue():
The required date argument is normally a string expression
representing a date from January 1, 100 through December 31, 9999.
However, date can also be any expression that can represent a date, a
time, or both a date and time, in that range.
The success of these two functions might also depend on input date formatting and system locale.

Checking for date overlap across multiple date range objects

I have several records in a database that have Start and End Dates
09/15/2011 - 09/30/2011
10/15/2011 - 10/22/2011
11/01/2011 - 11/15/2011
When user stores a record, I need to make sure dates don't overlap.
My simple code checks date ranges within a specific record (e.g. user enters 9/16/2011 or 10/21/2011, I throw an exception.)
But, on the slim chance a user gets creative (e.g. 10/14/2011 - 10/23/2011 or even 10/14/2011 to 11/16/2011), now they have circumvented my check.
BTW, the user could enter 10/14/2011 to 10/23/2011 if they were editing the record that contained values 10/15/2011 - 10/22/2011.
So, I'm trying to solve this riddle with a linq query. However, what I have isn't working exactly right.
UPDATE Nevermind about code not working. While trying to provide an example to expand on Miika's repsonse, I found my answer. So, giving credit to Miika for pointing me in the right direction and posting my working code below:
Here's my code:
Private Sub CheckForOverlap(myMonth As Messages.MyMonth)
Dim am As New MyMonth()
Dim amCollection As Messages.MyMonthCollection
Dim overlappingMyMonthDate As Boolean = False
Dim sErrorMsg As String = ""
'...non-applicable code omitted
Dim query = From s In amCollection _
Let s1 As MyMonth = CType(s, MyMonth) _
Where s1.AttendanceMonthID <> attendanceMonth.AttendanceMonthID And _
(CDate(attendanceMonth.StartDate) < CDate(s1.StartDate) And CDate(attendanceMonth.EndDate) > CDate(s1.EndDate)) _
Select s1
If query.Count > 0 Then
sErrorMsg = "Dates entered surround another entry"
End If
If overlappingMyMonthDate Then
Throw New Exception(sErrorMsg)
End If
End Sub
End Class
It all came down a LINQ query.
Do you need to do it in code or would SQL be an option? If the data is in a database, you could use the following query to check for overlaps.
SELECT COUNT(*)
FROM Table1
WHERE Table1.StartDate < 'endCheckDate'
AND Table1.EndDate > 'startCheckDate'
This will return a count of the number of overlaps found. 'endCheckDate' and 'startCheckDate' are your new query values (in date format). If your data is in a object collection in memory, then you could use LINQ. If you need help with a LINQ statement, let me know.

How to give the dtpicker date – 1?

Now using VS 2008
Before I used VB 6, now I Upgraded to VB 2008.
VB6 Code
sdate = DateToString(dtpicker1 - 1)
edate = DateToString(dtpicker2)
Above code is working fine.
After Upgraded to VB 2008
sdate = DateToString(dtpicker1._Value)
edate = DateToString(dtpicker2._Value)
If I Put
sdate = DateToString(dtpicker1._Value - 1)
It is showing Error.
How can I write a code like dtpicker1 – 1
Need VB code Help.
The Value is of type Object.
That is because the value of a datepicker can be either a valid date, or empty. So you need:
If IsDate(dtpicker1._Value) Then
sdate = CDate(dtpicker1._Value).AddDays(-1).ToShortDateString()
End If
If the value is empty, it actually has a type of System.DBNull , which means that for conversion to string, you can define two functions with identical names, but different parameter types:
Public Function DateToString(ByVal _date As Date) As String
Return _date.ToShortDateString()
End Function
Public Function DateToString(ByVal _date As DBNull) As String
Return "No date selected!"
End Function
You can then modify your previous code to this:
Dim theDate As Object
theDate = dtpicker1._Value
If IsDate(theDate) Then
theDate = CDate(theDate).AddDays(-1)
End If
sdate = DateToString(theDate)
I'm assuming you're trying to subtract one day from dtpicker1's value? If so, do this:
sdate = DateToString(dtpicker1._Value.AddDays(-1))
Bit unsure of what you are trying to do, but for the following solution I'm assuming that by -1 you are saying that you want to get the day before the date.
If so then use
dtpicker1._Value.AddDays(-1).ToString
On top of that if you want to format the string that comes out, you can do that by using a format string such as
dtpicker1._Value.AddDays(-1).ToString("dd/MM/yyyy")
which will print the date out like "20/08/2009".