MSAccess query between two time fields when adding fields together works fine when subtracting gives error - ms-access-2010

I have two fields on a query MinOfClocked_Time and MaxOfClocked_Time, When adding the two with the following code
TimeWorked: [MaxOfClocked_Time]+[MinOfClocked_Time]
and i get a result of 07:0207:02, But if I Subtract them
TimeWorked: [MaxOfClocked_Time]-[MinOfClocked_Time]
then i get #Error, So i now the format is correct but not subtracting the two fields. Can any please point me in the right direction.

In fact, when you subtract one time from another you are actually subtracting two numbers.
see the negative date is not possible in ms access.
and use Datediff instead.

TimeWorked:=([MaxOfClocked_Time]-[MinOfClocked_Time])*24
Try that.

You get that error, because your "times" are stored as text.
[MaxOfClocked_Time] = "07:02"
[MinOfClocked_Time] = "07:02"
' Concatenate the text times:
? [MaxOfClocked_Time]+[MinOfClocked_Time]
07:0207:02
' Cannot "subtract" text:
? [MaxOfClocked_Time]-[MinOfClocked_Time]
#Error
However, true time values can easily be added or subtracted, say:
' Text:
[MaxOfClocked_Time] = "14:27"
[MinOfClocked_Time] = "09:42"
' Date:
MaxTime = CDate([MaxOfClocked_Time])
MinTime = CDate([MinOfClocked_Time])
? MaxTime - MinTime
0.197916666666667
? CDate(MaxTime - MinTime)
04:45:00
' However, a negative value will not be shown when converted to Date:
? MinTime - MaxTime
-0.197916666666667
? CDate(MinTime - MaxTime)
04:45:00
To display a negative time, use Format:
Format(MaxTime - MinTime, ";-") & Format(MaxTime - MinTime, "hh:nn")
04:45
Format(MinTime - MaxTime, ";-") & Format(MinTime - MaxTime, "hh:nn")
-04:45
This, of course, only works as intended when the time span is within 24 hours.
If 24 hours or more, use a custom function like this:
Public Function FormatHourMinuteDiff( _
ByVal datTimeStart As Date, _
ByVal datTimeEnd As Date, _
Optional ByVal strSeparator As String = ":") _
As String
' Returns count of days, hours and minutes of difference
' between datTimeStart and datTimeEnd converted to
' hours and minutes as a signed formatted string
' with an optional choice of time separator.
'
' Example:
' datTimeStart: #10:03#
' datTimeEnd : #20:01#
' returns : 9:58
'
' datTimeStart: #22:13#
' datTimeEnd : #3:45#
' returns : -18:28
'
' 2005-02-05. Cactus Data ApS, CPH.
Const cintMinutesHour As Integer = 60
Dim lngMinutes As Long
Dim strHour As String
Dim strMinute As String
Dim strHourMinute As String
lngMinutes = DateDiff("n", datTimeStart, datTimeEnd)
strHour = CStr(lngMinutes \ cintMinutesHour)
' Add leading zero to minute count when needed.
strMinute = Right("0" & CStr(Abs(lngMinutes) Mod cintMinutesHour), 2)
strHourMinute = strHour & strSeparator & strMinute
FormatHourMinuteDiff = strHourMinute
End Function

Related

Checking content of textbox vb.net

I am using a text box for input to my SQL query. Based on the input I create a certain query and display the data in a gridview.
However I wish to make an adjustment for my users.
They often make an input like PL26... However this is not a valid name in the database to search for. Therefore I want to CHECK their input, and alter it accordingly, so they don't have to think about it.
I happen to know that when they type PL26 the correct input would be PL000026 ... The entity to search for is always "PL" + 6 characters/numbers... so if they wrote PL155, the number/string I pass to the sql query should become PL + 000 + 155 = PL000155.
I hope someone can help me how to accomplish this. That is if it is possible?
My idea/Pseudo code would be something like
If tbInput.txt's FIRST 2 CHARS are PL, then check total length of string
if StringLength < 8 characters, then
if length = 2 then ADD 4 0' after PL...
if length = 3 then add 3 0's after PL...
if length = 3 then add 3 0's after PL..
etc
....
...
Here we go:
Private Sub Button21_Click(sender As System.Object, e As System.EventArgs) Handles Button21.Click
Debug.Print(formatCode("PL1"))
Debug.Print(formatCode("PL"))
Debug.Print(formatCode("PL01"))
Debug.Print(formatCode("PL155"))
End Sub
Private Function formatCode(userInput As String) As String
Dim returnVal As String
If userInput.Length < 8 Then
returnVal = String.Concat(userInput.Substring(0, 2), userInput.Substring(2, userInput.Length - 2).PadLeft(6, "0"))
Else
returnVal = userInput
End If
Return returnVal
End Function
You may need to add some validation ensuring it starts with PL etc.
The following will work as long as there are no other non-numeric characters in between the PL and the numbers. You can always add it in your validation.
Dim newInput As String
If (input.StartsWith("PL")) Then
input = input.Remove(0, 2)
End If
' If this fails then it means the input was not valid
Dim numberPart = Convert.ToInt32(input)
newInput = "PL" + numberPart.ToString("D6")
Exctract a number by removing prefix "PL"
Parse to Integer
Use Custom Numeric Format Strings(zero placeholder) for adding zeros and prefix
Const PREFIX As String = "PL"
Dim exctractedNumber As Int32
If Int32.TryParse(tbInput.txt.Replace(PREFIX, String.Empty), exctractedNumber) = False Then
'Error nahdling
Exit Sub
End If
Dim finalFormat As String = String.Format("'{0}'000000", PREFIX)
Dim finalValue As String = exctractedNumber.ToString(finalFormat)
I would make use of the handy PadLeft method:
Dim input As String = "PL26"
Dim number As String = input.Substring(2, input.Length - 2)
If number.Length <> 6 Then
number = number.PadLeft(6, "0"C)
End If
MSDN String.PadLeft

Access 2010 sql query to format 14 character finance data

I have raw finance text files that I'm importing into Access 2010 and exporting in Excel format. These files contain several 14 character length fields which represent dollar values. I'm having issues converting these fields into currency because of the 14th character. The 14th character is a number represented by a bracket or letter. It also dictates whether the unique field is a positive or negative value.
Positive numbers 0 to 9 start with open bracket { being zero, A being one, B being two,...I being nine.
Negative numbers -0 to -9 (I know, -0 is a mathematical faux pas but stay with me. I don't know how else to explain it.) start with close bracket } being -0, J being -1,K being -2,...R being -9.
Example data (all belonging to the same field/column):
0000000003422{ converted is $342.20
0000000006245} converted is -$624.50
0000000000210N converted is -$21.05
0000000011468D converted is $1,146.84
Here's the query that I'm working with. Each time I execute it, the entire field is deleted though. I would prefer to stick to a SQL query if possible but I'm open to all methods of resolution.
SET FIELD_1 = Format(Left([FIELD_1],12) & "." & Mid([FIELD_1],13,1) & IIf(Right([FIELD_1],1)="{",0,IIf(Right([FIELD_1],1)="A",1,IIf(Right([FIELD_1],1)="B",2,IIf(Right([FIELD_1],1)="C",3,IIf(Right([FIELD_1],1)="D",4,IIf(Right([FIELD_1],1)="E",5,IIf(Right([FIELD_1],1)="F",6,IIf(Right([FIELD_1],1)="G",7,IIf(Right([FIELD_1],1)="H",8,IIf(Right([FIELD_1],1)="I",9,"")))))))))),"$##0.00"), IIf(Right([FIELD_1],1)="}",0,IIf(Right([FIELD_1],1)="J",1,IIf(Right([FIELD_1],1)="K",2,IIf(Right([FIELD_1],1)="L",3,IIf(Right([FIELD_1],1)="M",4,IIf(Right([FIELD_1],1)="N",5,IIf(Right([FIELD_1],1)="O",6,IIf(Right([FIELD_1],1)="P",7,IIf(Right([FIELD_1],1)="Q",8,IIf(Right([FIELD_1],1)="R",9,"")))))))))),"-$##0.00")
here is a function that you can call to convert an input string like the ones in your example into a string formatted as you desire.
Private Function ConvertCurrency(strCur As String) As String
Const DIGITS = "{ABCDEFGHI}JKLMNOPQR"
Dim strAlphaDgt As String
Dim intDgt As Integer, intSign As Integer
Dim f As Integer
Dim curConverted As Currency
strAlphaDgt = Right(strCur, 1) ' Extract 1st char from right
f = InStr(DIGITS, strAlphaDgt) ' Search char in DIGITS. Its position is related to digit value
intDgt = (f - 1) Mod 10 ' Converts position into value of the digit
intSign = 1 - 2 * Int((f - 1) / 10) ' If it's in the 1st half is positive, if in the 2nd half of DIGITS it's negative
curConverted = intSign * _
CCur(Left(strCur, Len(strCur) - 1) & _
Chr(intDgt + 48)) / 100 ' Rebuild a currency value with 2 decimal digits
ConvertCurrency = Format(curConverted, _
"$#,###.00") ' Format output
End Function
If you need to have a Currency as returned value, you can change the type returned from String to Currency and return the content of curConverted variable.
Bye.

Add Days to Date with 'YYYYMMDD' format

In VB6, I am trying to add days to a date which is in the format 'YYYYMMDD'. I can add days like this:
Pull_Date = Need_Date + Val(txtLeadTime.Text)
which works, until the resulting days is greater than the number of days in the month. I tried using DateAdd, but it doesn't accept the YYYYMMDD format - neither does CDate.
You need to convert your date string to a date so you can use the DateAdd function:
Dim Need_Date As String
Dim Pull_Date As Date
Dim tmpDate As Date
Need_Date = "20141113"
tmpDate = CDate(Mid$(Need_Date, 5, 2) & "/" & Right$(Need_Date, 2) & "/" & Left$(Need_Date, 4))
Pull_Date = DateAdd("d", Val(txtLeadTime.Text), tmpDate)
MsgBox Format$(Pull_Date, "yyyymmdd") '// if LeadTime is 25 days, displays 20141208
Please note, parsing your Need_Date by character position can blow up if it's not formatted exactly as expected.
After digging deeper into this old code, I found that a conversion function was already created:
Public Function Date_Format_YYYYMMDD(ByVal sDate As String) As String
If IsDate(sDate) Then
sDate = Format(sDate, "YYYYMMDD")
End If
Date_Format_YYYYMMDD = sDate
End Function
With this function, it's really easy:
Pull_Date = Date_Format_YYYYMMDD(Need_Date) + Val(txtLeadTime.Text)
The only thing I don't understand is why
Pull_Date = Format(Need_Date, "YYYYMMDD") + Val(txtLeadTime.Text)
doesn't work. Seems like it's doing the same thing as the function.

VBA Excel create hour column (like in a calendar) according to given time resolution

I need to create some sort of a calendar in VBA.
I need to create a column of hours. The time difference between 2 adjacent cells is determined by an integer read from a text file, which represents the time resolution in minutes.
For example - if Res = 60, the hour column should look like this:
12:00
13:00
14:00
...
if Res = 30, the hour column should look like this:
12:00
12:30
13:00
13:30
14:00
....
I've calculated the number of cells according to the given resultion (if Res = 60, nCells = 24, if Res = 30 nCells = 48 and so on). I just don't know how to create the hour column (in VBA code of course).
Thanks,
Li
You could use DateAdd to increment dates: http://www.techonthenet.com/excel/formulas/dateadd.php
Sub createTimeColumn()
intIncr = 60 'minutes to add each cell
intCellCnt = 1440 / intIncr '24h * 60m = 1440 minutes per day
datDate = CDate("01/11/2013 06:00:00") 'start date+time for first cell
For i = 1 To intCellCnt 'loop through n cells
Cells(i, 1) = Format(datDate, "hh:mm") 'write and format result
datDate = DateAdd("n", intIncr, datDate) 'add increment value
Next i
End Sub
Result will look like
You need a simple loop to which you pass the start range, begin & end time and increment. I recommend to strictly work with dates/times; the output range should be formatted as time
Sub CallTest()
FillIt [A1], #12:00:00 PM#, #1:00:00 PM#, #12:10:00 AM#
End Sub
Sub FillIt(RStart As Range, TStart As Date, TEnd As Date, Inc As Date)
Dim Idx As Integer, TLoop
Idx = 1
TLoop = TStart
Do
RStart(Idx, 1) = TLoop
TLoop = TLoop + Inc
Idx = Idx + 1
Loop Until TLoop > TEnd + #12:00:01 AM# ' need to add 1 second to really
' break the loop where we want
End Sub
Don't worry about the somewhat strange looking Inc parameter .... in VBA editor just enter #0:10:0# ... it will automatically expand to a full 24 hrs AM/PM notation.
The 1 second in the Loop Until is added because I found that the loop is left 1 pass too early (it seems that within the loop #16:0:0# < #16:0:0# resolves to True)
Public Sub MakeTime(RangeA As Range, iRes As Long)
Dim dDate As Date
Dim rCell As Range
Dim X As Variant
Set rCell = RangeA
dDate = CDate(RangeA.Value)
Do
dDate = DateAdd("n", iRes, dDate)
Set rCell = rCell.Offset(1, 0)
rCell.Value = dDate
Loop Until DateDiff("h", CDate(RangeA.Value), dDate) >= 24
End Sub
Sub test()
Call MakeTime(Sheet1.Range("A1"), 45)
End Sub
They beat me to it... But since I've already written a routine... Might as well post it :)
Try this in a new workbook
Sub Main()
' ask for column input
Dim myColumn As String
myColumn = InputBox("Please enter the column letter where the hours will be stored")
' Clear the column
Columns(myColumn & ":" & myColumn).ClearContents
' initial hour
Dim firstHour As String
firstHour = InputBox("Please enter the start time in the hh:mm format i.e. 12:00")
' interval
Dim interval As Long
interval = CLng(InputBox("Please enter the interval in minutes"))
' duration
Dim duration As Long
duration = CLng(InputBox("Please enter the duration (hrs)"))
' apply formatting to column
Columns(myColumn & ":" & myColumn).NumberFormat = "hh:mm;#"
' enter the initial time into cell
Range(myColumn & 1) = CDate(firstHour)
' fill in remaining hours / interval
Dim i As Long
For i = 1 To (60 / interval) * duration
Range(myColumn & 1).Offset(i, 0) = DateAdd("n", interval, CDate(Range(myColumn & 1).Offset(i - 1, 0)))
Next i
End Sub

VB.NET Date Comparison Not Returning Correct Results?

I am pulling a date value from my database:
Dim qfresho = From p In dbConfig.Configs _
Where p.Description = "FROD" _
Select p.dateValue
Dim qfreshc = From p In dbConfig.Configs _
Where p.Description = "FRCD" _
Select p.dateValue
Then comparing these date values to the current date:
If qfresho.First.Value >= Date.Now And qfreshc.First.Value <= Date.Now Then
lblFreshman.Text = "Freshmen are currently eligible to register for a room."
Else
Dim frdays As TimeSpan
frdays = (qfresho.First.Value).Subtract(Now)
lblFreshman.Text = "Registration will open for freshmen in " & frdays.Days & " days."
End If
But for some reason its always returning the Else condition - even though the values in the database should make the query true. Any ideas? I'm guessing for some reason its not pulling the results as a date?
Date.Now returns a DateTime, so does your database have dates and times or just dates? If you just want the date, you can use Date.Today.
Do the dates have time components that could be throwing off the compares?
Why not just add two debugs before the comparison???
Debug.WriteLine(qfresho.First.Value.ToString("MM/dd/yyyy hh:mm:ss.ffff"))
Debug.WriteLine(qfreshc.First.Value.ToString("MM/dd/yyyy hh:mm:ss.ffff"))
That should help.

Resources