I need some assistance with writting a VB function to compare the system time with my column 1 datetime variables, and return a different color background. Here is the condition...
if scheduledTime is 0-15mins late, then background row color red
if scheduledTime is 15mins-30mins late, then background row color yellow
if scheduledTime is 30mins-2hours late, then background row color green
Row Rendered event:
Row_Rendered();
DateTime systemTime = DateTime.Now();
DateTime fieldTime = SCHD_DTM.CurrentValue;
DateTime result As Integer = DateTime.Compare(fieldTime,systemTime).TotalMinutes
if result <= 0.25 Then
RowATTrs("style") = "background-color:Red";
else if result > 0.25 & result <- 0.5 Then
RowATTrs("style") = "background-color:Yellow";
else if result > 0.5 & result <= 2 Then
RowATTrs("style") = "background-color:Green";
End If
This is what I had and Im getting no response...
"Im getting no response" is not a good description of an error or undesired behaviour. However, you are mixing C# and VB.NET in your code. Of course that won't compile.
But this should:
Dim systemTime As date = Date.Now
Dim fieldTime As Date = SCHD_DTM.CurrentValue
Dim result As Double= (fieldTime - systemTime).TotalMinutes
If result <= 0.25 Then
RowATTrs("style") = "background-color:Red"
ElseIf result > 0.25 & result < -0.5 Then
RowATTrs("style") = "background-color:Yellow"
ElseIf result > 0.5 & result <= 2 Then
RowATTrs("style") = "background-color:Green"
End If
However, not sure if fieldTime is supposed to be lower than Date.Now. Then swap the variables in (fieldTime - systemTime).
You can use the datediff function to find out what you want,
DateDiff(DateInterval.Minute, systemTime, fieldTime)
will return a long telling you the number of minutes between the two datetimes.
Related
Trying another attempt at this question:
With the below code, I'm trying to articulate a date range; May 10 - June 8th. I'm outputting a unique thumbnail image per date in this range (coming together as a stylized calendar of sorts); I need to also detect, within this range, today's date. As a .today style class will be appending for today's date. I achieved this previously when the date range was just within one month, 1 - 31 (and that code is under the most recent attempt / which is original code) this same code could not work because now it's not as simple as 1 - 31 and declaring the month name statically, now it's two months and 10 - 31 and then 1 - 8. Also, not my most recent attempt fails so hard the page doesn't even compile and is just white.
<%
Dim d1 As New Date(2015, 5, 10)
Dim d2 As New Date(2015, 6, 8)
Dim DaysBetween As Long = DateDiff(DateInterval.Day, d1, d2)
Dim d3 As Date
For d As Long = 0 To DaysBetween
d3 = d1.AddDays(d)
If d3 < Today() Then
time = "past"
ElseIf d3 = Today Then
time = "today"
Else
time = "future"
End If
Dim suffix As String = Suffixer(d3.Day)
response.write("<section id='day_"& i &"' class='calSquare " & time &"'><article class='dateImage' style='background-image: url(images/Calendar_Thumbnails/Day_"&i&".jpg)'></article></article><article class='dateTitle'> "&i&suffix&"</article></section>")
Next
<!--response.write(products(0))-->
%>
Original functional code; articulating one month.
<%
For i = 1 to 31
dim time
If i < day_part Then
time = "past"
ElseIf i = day_part Then
time = "today"
Else
time = "future"
End If
suffix = Suffixer(i)
response.write("<section id='day_"& i &"' class='calSquare " & time &"'><article class='dateImage' style='background-image: url(images/Calendar_Thumbnails/Day_"&i&".jpg)'></article></article><article class='dateTitle'>May "&i&suffix&"</article></section>")
Next
<!--response.write(products(0))-->
%>
Your first code sample isn't valid VBScript. The language doesn't support constructs like Dim var As type = value, so that's probably why the page isn't displayed.
As for listing the dates within a range while highlighting the current date, you could do something like this:
today = Date
firstDay = DateValue("2015-05-10")
lastDay = DateValue("2015-06-08")
d = firstDay
While d <= lastDay
If d = today Then
response.write "today"
Else
response.write "other day in range"
End If
d = d + 1
Wend
After searching the forum, I did not find a good solution for this question. If I missed it, please tell me.
I need to count the unique values in one column in EXCEL 2010.
The worksheet has 1 million rows and 10 columns. All cell values are string or numbers.
I used the solution at Count unique values in a column in Excel
=SUMPRODUCT((A2:A1000000<>"")/COUNTIF(A2:A100000,A2:A1000000&""))
But, it runs so long time that the EXCEL is almost frozen. And, it generates 25 processes in Win 7.
Are there more efficient ways to do it?
Also, in the column, all values have for format of
AX_Y
here, A is a character, X is an integer, Y is an integer from 1 to 10.
For example, A5389579_10
I need to cut off the part after (including) undersocre. for the example,
A5389579
This is what I need to count as unique values in all cells in one column.
For example, A5389579_10
A1543848_6
A5389579_8
Here, the unique value has 2 after removing the part after underscore.
How to do it in EXCEL VBA and R (if no efficient solution for EXCEL)?
If you want to do this by VBA, you can take advantage of the Collection object. Since collections can only contain unique values, trying to add all of your input data to a collection will result in an array of unique values. The code below takes all the variables in a selected range and then outputs an array with distinct values to an other sheet (in this case a sheet named Output).
Sub ReturnDistinct()
Dim Cell As Range
Dim i As Integer
Dim DistCol As New Collection
Dim DistArr()
Dim OutSht As Worksheet
Dim LookupVal As String
Set OutSht = ActiveWorkbook.Sheets("Output") '<~~ Define sheet to putput array
If TypeName(Selection) <> "Range" Then Exit Sub
'Add all distinct values to collection
For Each Cell In Selection
If InStr(Cell.Value, "_") > 0 Then
LookupVal = Mid(Cell.Value, 1, InStr(Cell.Value, "_") - 1)
Else
LookupVal = Cell.Value
End If
On Error Resume Next
DistCol.Add LookupVal, CStr(LookupVal)
On Error GoTo 0
Next Cell
'Write collection to array
ReDim DistArr(1 To DistCol.Count, 1 To 1)
For i = 1 To DistCol.Count Step 1
DistArr(i, 1) = DistCol.Item(i)
Next i
'Outputs distinct values
OutSht.Range("A1:A" & UBound(DistArr)).Value = DistArr
End Sub
Note that since this code writes all the distinct values to a single column in the OutSht-sheet, this will return an error if there are more than 1,048,576 distinct values in your dataset. In that case you would have to split the data to be filled into multiple output columns.
For your specific request to count, use the below in a formula like =COUNTA(GetUniques(LEFT("A1:A100000",FIND("_","A1:A100000")-1)) entered as an array formula with Ctrl+Shift+Enter.
It also accepts multiple ranges / values (e.g. GetUniques("A1:A10","B2:E4"))
Function GetUniques(ParamArray args())
Dim arg, ele, arr, i As Long
Dim c As Collection
Set c = New Collection
For Each arg In args
If TypeOf arg Is Range Then
If arg.Count = 1 Then
arr = array(arg.value)
Else
arr = arg.Value
End If
ElseIf VarType(arg) > vbArray Then
arr = arg
Else
arr = Array(arg)
End If
For Each ele In arr
On Error Resume Next
c.Add ele, VarType(ele) & "|" & CStr(ele)
On Error GoTo 0
Next ele
Next arg
If c.Count > 0 Then
ReDim arr(0 To c.Count - 1)
For i = 0 To UBound(arr)
arr(i) = c(i + 1)
Next i
Set c = Nothing
GetUniques = arr
End If
End Function
edit: added a performance optimisation for ranges (loads them at once into an array - much faster than enumerating through a range)
In R:
# sample data
df <- data.frame(x=1:1000000,
y=sample(1e6:(1e7-1),1e6,replace=T))
df$y <- paste0("A",df$y,"_",sample(1:10,1e6,replace=T))
# this does the work...
length(unique(sub("_[0-9]+","",df$y)))
# [1] 946442
# and it's fast...
system.time(length(unique(sub("_[0-9]+","",df$y))))
# user system elapsed
# 2.01 0.00 2.02
In excel 2010... in the next column add (if original data was in A:A add in B1)
= 1/COUNTIF(A:A,A1) and copy down col B to the bottom of your data. Depending on your PC it may chug away calculating for a long time, but it will work. Then copy col B & paste values over itself.
Then SUM col B
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
Working on a website that's a combination of Jquery Mobile and ASP 4. Currently I'm stuck on a form I'm trying to get to do a SQL insert. I'm trying to use code behind in VB to handle my insert...
All that to say: I need my page to convert a minute value into hour&quarter hour format, rounding to nearest quarter hour.
Currently I'm taking two times entered into text boxes (ex. 8:00:00 AM and 9:12:00 AM). If I use a TimeSpan I can calculate the difference between the two values and dump that difference into a variable, for example tElapsed = tSpan.TotalMinutes.ToString would set tElapsed = 72 for the above times. I need to convert this to a 1.0hr, 1.25hr, 1.5hr, etc format and round 3+ minutes to next half hour... and I keep getting stuck.
Synopsis:
Have:
Text Box: Time1 = 8:00:00 AM
Text Box: Time2 = 9:12:00 AM
Dim tDiff As String = DateTime.Parse.(Time2.Text) - DateTime.Parse(Time1.Text)
Dim tElapse As String = tDiff.TotalMinutes.ToString
tElapse will return 72 for the above, now I need to convert 72 (minutes) to 1.25 (hours).
1.25 hours can be any of: 64 minutes - 78 minutes
Any help would be appreciated...
You can use Math.DivRem
int remainder;
int whole = Math.DivRem(tDiff.TotalMinutes, 60, out remainder);
At this point remainder will now be what's left between hours. 0 to 59 minutes. I wasn't clearn on how you wanted exactly to round that, but (double)remainder / 60.00 will give you the decimal place, which you can then add to the whole.
Here is the solution I used, posting it as an answer so the code structure will show up:
Dim tDiff As TimeSpan = DateTime.Parse(textboxEnd.Text) - DateTime.Parse(textboxStart.Text)
Dim mins As Integer = tDiff.TotalMinutes.ToString
Dim remainder As Integer
Dim hrs As String = Math.DivRem(mins, 60, remainder)
Dim qtyorder As String
Select Case remainder
Case 1 To 2
qtyorder = hrs
Case 3 To 18
qtyorder = hrs & ".25"
Case 19 To 28
qtyorder = hrs & ".50"
Case 29 To 48
qtyorder = hrs & ".75"
Case Else
qtyorder = (hrs + 1) & ".00"
End Select
lblResult.Text = qtyorder
I need to retrieve the current date in asp.net and then compare that with the date given by the user in textbox1.text(mm/dd/yyyy format), if date date given is greater than current date then error else add 4months2days with that date and display it in textbox2.text.
help me please,
thanking you guys,
Indranil
DateTime dateToCompare;
if(DateTime.TryParse(textbox1.text, out dateToCompare))
{
DateTime current = DateTime.Now;
TimeSpan ts = current - dateToCompare;
if (ts.Ticks < 0)
{
//display error
}
else
textbox2.text = dateToCompare.AddMonths(4).AddDays(2).ToString("mm/dd/yyyy");
}
}
I'm not going to write your code, but in .NET you can use ToString to specify a date format, TryParse to get a date out of a string. And AddDays, AddMonths etc to manipulate a date.
In javascript, there's no simple way to format output, but you can use getMonth etc to prompt the individual values and concatenate a string from that. You can use a combination of getDate and setDate to manipulate dates. It automatically corrects for new months, i.e. if you run myDate.setDate( myDate.getDate() + 60 ) it'll actually increment by 60 days; you won't end up with a weird date like May 74th.
Keep in mind that months in javascript are zero-based, ie January is 0, February is 1, etc.
You can create a new date in javascript by new Date(yy, mm, dd) or new Date('yy/mm/dd'), so you could string-manipulate an input and create a date from that.
To compare two dates, you can subtract one from the other, and get the difference in milliseconds.
if ( dateA - dateB < 0 ) // dateB is greater than dateA (occurrs later)
and
var diff = Math.abs(dateA - dateB) // difference in ms, no matter which date is greater
DateTime date1 = new DateTime();
if(DateTime.TryParse(textbox1.text, out date1)){
if (date1.CompareTo(DateTime.Now) > 0)
{
//Error code here
}else
{
textbox2.text = date1.AddMonths(4).AddDays(2);
}
}