I have a macro set up that will clear content on a spreadsheet. At the end of this Macro, I want to select specific cells that already have dates in them and then replace the current dates with current date +1. After searching the web I found the DateAdd function, but I am pretty new to VBA and I am having difficulty writing the function correctly. After selecting the necessary cells, how would I go about changing the dates to the next day?
Taking your question literally, you could do this:
' Here goes the code where you select the date cells you want to increment
' ...
' Now increment them by 1 day:
Dim cell As Range
For Each cell In Selection
cell.Value = cell.Value + 1 ' adds 1 day
Next cell
The unit of the Date data type is a day. So adding 1 adds one day.
Here's an example of how to use DateAdd:
Range("A1").value = DateAdd("d", 1, CDate(Range("A1")))
This, of course, assumes a valid date is in A1. It will increment that date by a single day.
"d" means we are adding a day. Here are the other intervals for adding years, months, etc.
yyyy - Year
q - Quarter
m - Month
y - Day of year
d - Day
w - Weekday
ww - Week
h - Hour
n - Minute
s - Second
Notice I use CDate. That simply converts the value of range("a1") into a date. It will throw an error if A1 cannot be parsed as a date.
Of course, you can also use this method to subtract days:
Range("A1").value = DateAdd("d", -3, CDate(Range("A1")))
This subtracts three days for the date in A1.
If you have date in cell a1 and want increment one day, it should be as simple as
range("a1").value = range("a1").value + 1
Related
I have a financial sheet and I want to record my monthly final balance each month but automatically. This is my sheet:
I tried this code:
Public Sub DATA()
If Today > 31 / 3 / 2021 Then
Range("L10").Value = Range("I16").Value
Else
End If
End Sub
The Idea is to copy/paste a value from one cell to another only in the last day of the month and keep this value there forever. For example:
at 31/03/2021, I would run the macro and it would copy/paste the final balance of this month to the "Março" cell in the right, and this value would stay there.
I'm new to VBA so, can anybody tell me what I'm doing wrong? Thanks!
From comments:
what I'm trying to do is to copy the value of an specific cell to another one, only when the day is the last of the month.
Use WorksheetFunction.EoMonth with 0 as the second argument:
If Date = WorksheetFunction.EoMonth(Date, 0) Then
Range("L10").Value = Range("I16").Value
End If
I just want to create list of months automatically between start and end dates in which if the starting date or the end date have only dates then it comes as date from to in excel.
If A1 contains the starting date, and A2 is the enddate, then
=TEXT(IF(EDATE($A$1,ROW() - 5) <= $A$2, EDATE($A$1,ROW() - 5), ""), "mmmyy")
does what you ask for. Just apply it for sufficiently many cells.
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
I am trying to filter data in a pivot table. I need to set Monday as the first day of the week. The default is Sunday. Do you know how to set it?
Edit1: I am trying to do dynamic filtering using THIS WEEK. As the default is Sunday, the result is not what I exactly expect.
Edit2: Current solution using VBA. I am still looking for a neater solution.
Sub YmThisWeek()
'
' YmFinal Macro
'
'
Dim startDate, endDate As Date
endDate = Date
startDate = endDate - 7 ' 7 DAYS IN A WEEK
'Pick the star of the week
'vbSunday 1 Sunday (default used)
'vbMonday 2 Monday
'vbTuesday 3 Tuesday
'vbWednesday 4 Wednesday
'vbThursday 5 Thursday
'vbFriday 6 Friday
'vbSaturday 7 Saturday
Do While (startDate < endDate - 1) And Not Weekday(startDate) = 2 '<- week start day
startDate = startDate + 1
Loop
ActiveSheet.PivotTables("pvtTbl").PivotFields("Date").ClearAllFilters
ActiveSheet.PivotTables("pvtTbl").PivotFields("Date").PivotFilters.Add Type:= _
xlDateBetween, Value1:=Format(startDate, "dd/mm/yyyy"), Value2:=Format(endDate, "dd/mm/yyyy")
End Sub
Good question. And I don't have the perfect answer.
But this workaround might get you going.
Click on 'Sunday'
Drag it to the end of the Pivot table
You could do this with VBA. But a NON-VBA method you could use involves adding an extra column to your data. Label it THIS WEEK. Then populate that with a formula that returns TRUE or FALSE depending on your definition of the week. For example, if THIS WEEK is from the most recent Monday to the following Saturday, compared with a date stored in cell F1, then the formula would be:
=AND(A2>=($F$1+1-WEEKDAY($F$1-1)),A2<=($F$1+7-WEEKDAY($F$1-1)))
I used a cell reference for testing purposes, and I would advise you to do the same until you have things working the way you want. You can subsequently either change your cell so it contains =TODAY(), or you can substitute TODAY() in the formula.
You would then drag THIS WEEK to the filter area and filter on TRUE Whenever you Refresh your Pivot Table, the filter will update.
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"