Subtraction between to excel column using VBScript - excel

Suppose I have below excel sheet,And I need to find the difference between them and result need to put back to another column:
ColA ColB ColC
9/3/2012 8:31:59 AM 09/17/2012 6:45:56 PM Result
9/4/2012 8:31:59 AM 10/17/2012 6:45:56 PM Result
I did it using Loop and Row-By-Row technique. Looking for a way if it can be done directly by column level subtraction. Say ColB-ColA - > ColC. The whole operation should be performed at a time.Result should come "hh:mm:ss".
CODE
IntRow4=2
Do While objSheet4.Cells(IntRow4,1).Value <> ""
If objSheet4.Cells(IntRow4,9).Value <> "Open" Then
Date1=objSheet4.Cells(IntRow4,7).Value
Date2=objSheet4.Cells(IntRow4,8).Value
objSheet4.Cells(IntRow4,11)=TimeSpan(Date1,Date2)
End If
IntRow4=IntRow4+1
Loop
Update
ColA1 ColB1 ColC1 ColA2 ColB2 ColC2 ..... ColAN ColBN ColCN TotaltimeDurtion
Date Date 11:25:20 Date Date 10:25:00 Date Date 11:25:20 ?
here i have shown only one row,But there can be multiple or N number of rows.What I need to do is,I want to add the time durations and put them to the last colum "TotaltimeDurtion".But the last column can not be fixed.And all the columns for each row shouldn't required values,but all never will be empty.Can we also do this also in column level.here the duration is hh:mm:ss format or as per your instruction [h]:mm:ss. TotaltimeDurtion <- ColC1 + ColC2 + ...+ ColCN.

using the range object, I can set the formula on all the cells within a range at once
range("C1:C10").Formula="=B1-A1"
It will also adjust the formula based on the normal copying riles for absolute addressing.
e.g. with the above example, C10 will be =B10-A10. If I had put the formula as "=B1-$A$1" then C10 would have been =B10-$A$1

You can subtract one date from the other, and then set the formatting of the cell:
'Within the Do..While loop
Dim cell
Set cell = objSheet4.Cells(intRow4,11)
cell.Value = Date2 - Date1
cell.NumberFormat = "hh:mm:ss"

Related

VBA range.find finds wrong date value

I am looking up a price multiplier for a given date in an Excel sheet, but range.find gives the wrong date. Here are the relevant code snippets:
If Not IsWbOpen("daily_prices.xlsx") Then
Workbooks.Open "C:\.....\daily_prices.xlsx"
End If
Set daily = Workbooks("daily_prices.xlsx").Sheets(1)
daily.Range("A:A").NumberFormat = "dd/mm/yyyy"
End If
This part makes sure that the column A:A, which contains the dates, is formatted correctly.
The code then loops through a date range where d is a date between d1 and d2. In my test script, d1= Jan 1, 2023 (formatted as "01/01/2023"), and d2 = Jan 30, 2023 (formatted as "30/01/2023").
The Excel sheet "daily" has a header in row 1 and 49 different dates in column A, ordered chronologically from "11/01/2023" to "01/01/2024", and the related multiplier (k), starting in row 2.
Only the dates that have a multiplier defined are present in the sheet. The first group of dates is from "11/01/2023" at row 2 to "22/01/2023" at row 13, the next starts with "17/02/2023" at row 14, and so on. Dates in between have no multiplier, and thus are not present.
I search the multiplier with this part of the code:
Set c = daily.Range("A:A").Find(what:=d, After:=Range("A1"), LookIn:=xlValues) 'is this date in the daily prices?
If Not c Is Nothing Then
k = CDec(daily.Cells(c.Row, 4)) ' multiplier is in column 4 (D:D)
rate = rate * k
End If
As expected, c is NOTHING for all dates below "11/01/2023". When d = "11/01/2023", c becomes "not NOTHING" but strangely it returns "11/11/2023" instead of "11/01/2023", which is in row 40 instead of row 2, thus it fetches the multiplier of row 40 instead of row 2.
I have re-checked all the code after reading several similar cases and made sure that column A is formatted correctly as "date", but I still get "11/01/2023" wrongly 'found' at row 40 instead of row 2, and the value returned is "11/11/2023" instead of "11/01/2023".
Instead of "12/01/2023", it finds "31/12/2023", and instead of "14/01/2023", which is part of the dataset, it finds nothing.
What did I overlook, where is the error?
Eventually, I found the solution.
It appears that using dates formatted as dates leads to ambiguity with Range.Find(d) as it's very similar to a text search, and depending what date format you use, their partial strings (month and day) may create confusion in certain language versions of Windows. I noticed this when I was looking for a date with day=11 or 12 and found a date with month=11 or 12. This is typical for the confusion that occurs sometimes when you use data formats like "mm-dd-yyyy" (US) and "dd/mm/yyyy" (other) and looks like a Windows bug to me. Windows should distinguish the two formats clearly, but sometimes it doesn't.
There was a similar problem at VBA Range.Find method not finding a value that IS in the range that helped me find the solution.
I needed to format the search object temporarily as numbers
daily.Range("A:A").NumberFormat = "0"
and also search for the long integer value of the running date, thus the starting value is
d = CLng(date1)
where d is type number and date1 is type date. The search term is then simply
Set c = daily.Range("A:A").Find(d)
If Not c Is Nothing Then ...
At the end I reformat the date column with
daily.Range("A:A").NumberFormat = "dd/mm/yyyy;#"
This resolved the problem.
Thank you all for your kind help.
#Ron Rosenfeld's hint came closest as he proposed to search for What:=CDbl(date), which is what I am basically doing, except that I prefer CLng over CDbl as I need the date as an integer and not as a floating point number. The only problem with that idea was that you cannot search for .value2. You can only search for xlValues (which is not the same) or xlFormulas. Neither would find this long integer number in the cell's properties.
Transforming both the search object and the search item to numbers resolves the ambiguity completely.

change date format excel

I have the following date in excel "5/2/2020", I would like to obtain "5/Feb/2020", but unfortunately I am getting "May/2/2020".
Also tried to change the format of the cells , but excel still interprets that the first number is the month.
How do I tell Excel that the month is in the second position ?
Try:
If 5/2/2020 is in cell E5 then:
=VALUE(TEXT(E5,"d/mm/yyyy"))
and then custom number format this cell to d/mmm/yyyy
will yield 5/Feb/2020
OK, here is a new method tested with the following dates 5/2/2020, 22/2/2020, 22/12/2020, 12/2/2020.
This function splits the date numbers into 3 parts and places them into an array using the "/" as the split delimiter. It then reassembles the 3 parts in the order you wanted.
Step 1: Add the following Custom Function to a VBA Module:
Function Dates(Cell As Variant)
'Forces recalculation when call values are changed
Application.Volatile
Dim DateString As String
Dim DateArray() As String
DateString = Cell
DateArray = Split(DateString, "/")
Dates = DateArray(1) & "/" & DateArray(0) & "/" & DateArray(2)
End Function
Step 2: For example, enter the date you want to convert in Cell A1 (i.e. 5/2/2020).
Step 3: Put the function formula =VALUE(Dates(A1)) in Cell B1.
Step 4: Apply the custom number format to Cell B1: d/mmm/yyyy and the result will be 5/Feb/2020.
If you want to change the number format to mmm/dd/yyyy, then the result will be Feb/05/2020.
Note: the =VALUE(Dates(A1)) formula will work anywhere on the spreadsheet. All you have to do is change the cell reference A1 to another cell reference. You can also use the formula many times on the same spreadsheet.
Sammy

INDIRECT not working with ADDRESS to form range

I am trying to create a range which I will eventually want to find the minimum and maximum values with in. I am working with stock price data so the range will vary. I used ADDRESS to identify the beginning and end of the range:
Beginning:
=ADDRESS(MATCH(A2,SPYDATA,0),2)
where A2 is the beginning of the range and SPYDATA is the range of dates with open/high/low/close data in the adjacent columns. So the 2 represents the opening price on date A2. This works.
Ending:
=ADDRESS(MATCH(C2,SPYDATA,0),4)
where C2 is the end of the range and SPYDATA is the range of dates with open/high/low/close data in the adjacent columns. So the 4 represents the opening price on date C2. This works.
The problem comes when I try to concatenate them into a range that I could then use for =MIN and =MAX:
=INDIRECT(ADDRESS(MATCH(A2,SPYDATA,0),2) & ":" & ADDRESS(MATCH(C2,SPYDATA,0),4))
It worked once and after that when I tried different dates I get #spill error. The same error occurs now when I go back to the original dates.
Thanks

Getting Current Date and Return as Integer?

I have a date like this (mm/yy) in row 1
A B C D E F
1/19 2/19 3/19 4/19 5/19 6/19 ...
I want the VBA to recognize today's date and match it to current column and return as integer.
Ignoring the days (only matching month and year).
For example, if today is 4/13/2019, it would be 4 (column D)
I would need this in VBA because I will be using it to define a range:
For today To x month
It appears OP was looking for a VBA solution, so here is an alternative.
I can think of a few completely different methods of accomplishing this within VBA. Your question isn't very clear of what you are wanting the end result to be, but it appears you are looking for a function that will return the column number - perhaps so you can use to pinpoint a range.
Function DateCol(ByVal InputDate As Date) As Long
Dim colDate As Date
colDate = InputDate - Day(InputDate) + 1
Dim srcRng As Range
Set srcRng = ThisWorkbook.Worksheets("Sheet1").Rows(1)
DateCol = srcRng.Find(What:=colDate, LookAt:=xlWhole).Column
End Function
You simply take an input date, subtract the days (and add 1 since the first day of the month isn't 0). Then you take this new date and use the .Find() method to locate the range that contains your date on the worksheet, and finally the .Column property to get the number you are looking for.
Here is a small sample usage:
Sub test()
' Example Usage
Cells(10, DateCol(#6/11/2019#)).Value = "Test"
End Sub
In the above test sub, the DateCol() function would have returned the value of 6 in your sample worksheet, making the result:
Cells(10, 6).Value = "Test"
Only issue is that this function doesn't contain any error handling. You will raise an error if the date is not found in .Find(), so ensure that you take this into consideration.
Also, don't forget to change this line to use the true Worksheet:
ThisWorkbook.Worksheets("Sheet1").Rows(1)
I had to redo my answer after messing with the data. this is what i ended up with.
On Row 1 I entered the dates as: 1/1/2019, 2/1/2019, 3/1/2019... and custom formatted the row to only show it as mm/yy.
With the formula below I grab the month and year from the given date and convert it into the first of the month. I am very positive there is a better way to make it but my brain is fried for the day.
=MATCH(NUMBERVALUE(TEXT(A3,"mm")&"/1/"&TEXT(A3,"yy")),$1:$1,0)
Edit: (Edit formula to make it permanent on Row 1 [$1:$1])
Assuming that the date 4/13/2019 is on Cell A3

Excel - filter table results by dates

I have a refreshable table in excel and I want to filter the rows by a couple of date ranges. Each row has a date and other information.
I want to find the rows that are in the first date range (F1:F2) and are not in the second date range (H1:H2).
The table is refreshable, and can change size. It currently spans A3:X6146. The table is a query, so it will change sizes when a separate date range is used to find the table values.
I don't have much VBA experience, so this problem is tripping me up. Any ideas?
Thanks
EDIT:
I'll try to make the issue clearer.
I have a table that is created via a query that pulls in data that falls between the Starting Date and the Ending Date, 1/1/2016 and 12/31/2017 here. It lists each time an item was purchased, so each one can be listed multiple times.
I want to find which items were purchased (listed in the table) between the Active Date Range start and end dates (cells F1 and F2), and NOT purchased between the Inactive Date range (cells H1 and H2).
Starting Date: 1/1/2016 Active Date Range Start: 3/1/2016 Inactive Date Start: 3/2/2017
Ending Date: 12/31/2017 Active Date Range End: 3/1/2017 Inactive Date End: 9/22/2017
item date
1 9/21/2017
2 9/20/2017
3 9/20/2017
Yes, I can say to you what I would do.
Create one additional column to keep the result value, if is in or out of the date range. Then
dim t() as string, lin as long, linf as long
linf=Range("F65536").End(xlUp).Row 'or any other more precise way to get the final line
redim t(1 to linf-2,1 to 1)
'range dates - are they on the worksheet?
dim rg_dates as Range,r as range,b as boolean
set rg_dates=Sheets("xxxx").Range("B1:B4") ' just an example, the range would be B1:C4 but use only the first column - see below
For lin=3 to linf
b=False
For each r in rg_dates
If cells(lin,"F").value>= r.Cells(1,1) and cells(lin,"G").Value<=r.Cells(1,2).value then
b=true
Exit for
End If
Next r
If b then t(lin-2,1)="Y" else t(lin-2,1)="N"
Next l
Range("Z3:Z" & linf).Value = T
'Then just filter the table.
There would be then many things to do to keep it error free, and how to apply it at the concrete situation. Hopefully with what I wrote above you can get an idea about things you can do using VBA. If you are using code to filter the table you can do all this invisible to the user, creating an extra column for the filter criteria, filtering, and then deleting the whole column..

Resources