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
Related
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.
I'm new in the VBA world and just a beginner so sorry if the question is stupid:
From the Worksheet "Exclusive" (Workbook "Time.xlsx") I wanna copy all the values (String, Integer) within the range B1 to E500 into the Worksheet "ValueTime" of another Workbook "Ontime.xlsm
I did:
Workbooks("Time.xlsx").Worksheets("Time").Range("B1:B500, E1:E500").Copy
But this error follows:
"-2147352565(8002000b) unknown name"
I tried to solve this problem as follows:
Dim intcounter As Integer Dim strTransport As Integer
For intcounter = 1 To 255
If Cells("B1:B500, E1:E500", intcounter <> "") Then strTransport = Left(Cells("B1:B500, E1:E500", intcounter), 255)
Exit For
End If
Next intcounter
But it didn't help. The same error follows. What I wanted to do is that excel automatically deletes/crops out the last 255 characters (on another website someone also had the same problem and come to the conclusion that this error appears because 255 characters are too many) but it would be great if EVERY value can be copied and displayed
Another problem:
I also want to copy month and year of Workbook Time into the Worksheet "ValueTime" of the Workbook OnTime.
Month and year should be copied in two columns
I did:
Range("E1").Value = "Month"
Range("F1").Value = "Year"
ActiveChart.ChartTitle.Characters.Text = Format(Range("E1").Value, "mmmm")
ActiveChart.ChartTitle.Characters.Text = Format(Range("F1").Value, "yyyy")
Thank you so much in advance!
Wouldn't your very first line be:
Workbooks("Time.xlsx").Worksheets("Exclusive").Range("B1:E500").Copy
Since you said you're copying from the sheet "Exclusive"? Unknown name makes sense if you don't have a worksheet called "Time". If your range is B1 to E500, no need to separate it, just B1:E500 will do. How you formulated it, it would only select the B1 to B500 and E1 to E500 cells.
To copy this to the corresponding sheet:
Workbooks("Time.xlsx").Worksheets("Exclusive").Range("B1:E500").Copy: Workbooks("Ontime.xlsm").Worksheets("ValueTime").Range("A1") 'assuming you don't have anything in A-column yet since you start your month in E
For the month/year, it depends where your month/year comes from. Is it a single date in your OnTime? I would've asked in comment first but I'm not allowed yet.
EDIT:
Workbooks("Time.xlsx").Worksheets("Exclusive").Range("F2:F500").Copy Destination:= Workbooks("Ontime.xlsm").Worksheets("ValueTime").Range("E1") 'Since you're putting "Month" and "Year" as your headers, I hope your values in "Exclusive" also start in the second row
Workbooks("Ontime.xlsm").Worksheets("ValueTime").Range("E2:E500").Format = "mmmm"
Workbooks("Time.xlsx").Worksheets("Exclusive").Range("F1:F500").Copy Destination:= Workbooks("Ontime.xlsm").Worksheets("ValueTime").Range("F1")
Workbooks("Ontime.xlsm").Worksheets("ValueTime").Range("F2:F500").Format = "yyyy"
So to Format, copy values first, format after. Notice that the value of the date remains so you could technically copy the E-column from your Valuetime to F as well even after having formatted it to "mmmm".
In hindsight, setting the workbooks/worksheets to variables would've been a lot easier to read/write but since you're starting out, I didn't want to overwhelm you.
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..
Is there any way to COUNTIF it's the current date?
For example I have a spreadsheet with work orders, once the employee starts the work order it captures a time stamp, after the work order is completed it is moved to an archive, well I wanted to create a summary sheet that tells me how many orders we have done for that date, the format of the time stamp is:
2/19/2014 17:10:20
So basically I need a COUNTIF to count the column for the current date.
Is this possible?
The new version of Google Sheets has COUNTIFS, which would allow =COUNTIFS(A:A,">="&TODAY(),A:A,"<"&TODAY()+1)
You need to opt in to the new version to make it work, though. ("Try the new Google Sheets")
You would need to apply a function first on the range, which then makes COUNTIF not an appropriate function to count those dates matching 'today'. You can use SUMPRODUCT instead:
=arrayformula(SUMPRODUCT(1*(INT(A1:A100)=TODAY())))
INT strips out the time from the datetime.
If you don't have COUNTIFS available, as per maybeWeCouldStealAVan's suggestion, then you can use two COUNTIF functions like this
=COUNTIF(A:A,">="&TODAY())-COUNTIF(A:A,">="&TODAY()+1)
by counting all entries greater than or equal to today then subtracting all those greater than or equal to tomorrow the result is a count of those on today's date only
That formula will work in Excel or google - another option, similar to Jerry's is to use this googledocs specific formula
=count(filter(A1:A100,int(A1:A100)=today()))
try this:
dim i as integer
dim objDate as date
dim objStartDate as Date
dim objEndDate as Date
dim countOrders as integer
countOrders = 1
objStartDate = 'the start date to check with ( could be the start of the day)
objEndDate = 'the end date to check with (could be the end of the day)
for i = 1 to 'number of rows
objDate = CDate(cells(i, 1))
if (objDate > objStartDate) and (objDate < objEndDate) then
countOrders = countOrder +1
end if
next i
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"