Just starting to write VBA here, raw beginner.
I'm looking for help in fine-tuning my displayed date. With the help of examples I found online, I have a module to put the name of the last month, and year, into a cell in my Totals worksheet, and it does what I need to get by.
To make it perfect, though, I'd like to change what date info is displayed.
This is Excel in Office 365. I've searched for examples online and read tutorials about using DateAdd but can't find this anywhere. (Part of the problem is I'm so new, I don't know how to phrase things in vba-speak to find good answers!)
What I use now:
Sub PreviousMonthBasedOnCurrentMonth()
Dim ws As Worksheet
Set ws = Worksheets("Totals")
ws.Range("A1") = Format(DateAdd("m", -1, Date), "mmmm yyyy")
End Sub
This now inserts "February 1, 2019" into the cell - which is enough data for me to confirm which month I'm looking at. But ideally I'd like "February 1-28, 2019" (Or, say, "October 1-31, 2019" if I'm running this while in Nov).
How do I get the 'first day of month - last day of month' portion to display? Is that part of DateAdd, or more coding from scratch?
Not sure how to write something like that myself. Pointers to where to start would be great.
Try something like this:
Dim dt, dt2
dt = DateAdd("m", -1, Date) 'this time last month
dt2 = DateSerial(Year(Date), Month(Date), 1) - 1 'last day of previous month
Debug.Print Format(dt2, "mmmm") & " 1-" & Day(dt2) & " " & Format(dt2, "yyyy")
Note Excel will not see this as a date though...
You can also do it on one line this way:
Debug.Print Format(DateAdd("m", -1, Date), "mmmm") & " 1-" & Format(CDate(WorksheetFunction.EoMonth(DateAdd("m", -1, Date), 0)), "dd, yyyy")
OR
Debug.Print Format(DateAdd("m", -1, Date), "mmmm") & YourPartialDateVariableHere & Format(CDate(WorksheetFunction.EoMonth(DateAdd("m", -1, Date), 0)), "dd, yyyy")
Related
For whatever reason, everytime I try to use the Day(Now) function in VBA, it keeps displaying "1/9/1900". The Date function displays correctly, so I'm not sure what the issue here is.
Sub Test()
Dim datDay As Date
datDay = Day(Now)
MsgBox datDay
End Sub
Here's an image of the error.
The Day will be an integer somewhere between 1 and 31, depending on, well, the "day" part of the date returned by the DateTime.Now function.
The way dates are stored, they're essentially Double values, with the integer part being a number of days, and the decimal part being the time of day.
Debug.Print Format(CDate(0), "yyyy-mm-dd")
Output: 1899-12-30
We are June 10th, so the date value of 10 corresponds to January 9, 1900.
You want to store the value returned by Day, Month, and Year functions, into Long integer variables; not Date.
Dim datDay As Long
datDay = DateTime.Day(DateTime.Date) ' datDay is 10 because DateTime.Date is 2019-06-10.
Note: while unqualified Day, Date, Month, and Year (and others) functions work perfectly fine, it's probably a good idea to qualify them with the module they are declared in (VBA.DateTime), to avoid potentially confusing ambiguities, e.g. Date is both the name of a property of the DateTime module, and it's also a data type (Dim foo As Date), and the two have very different meanings.
Try:
Option Explicit
Sub Test()
Dim datDay As Date
datDay = Date
MsgBox "Whole date: " & datDay & vbNewLine & _
"Month: " & Month(Date) & " (" & Format(Date, "mmmm") & ")" & vbNewLine & _
"Day: " & Day(Date) & " (" & Format(Date, "dddd") & ")"
End Sub
Result:
Replace
datDay = Day(Now)
with
datDay = Day(Now())
Not sure if this will fix the problem, but =Day(Now()) works correctly when typed directly into a cell.
Your problem is datDay is typed as a Date. =Day(Now()) returns just 10, as today is June 10th. As a full Date value, this is 1/10/1900, since Excel indexes day 0 as 1/0/1900.
I am trying to open a file that has a title with the previous month in its name. For instance the file name is formatted as such: NAME year Month.xlsx. Currently I can get it to pull January, however the current month is May so I need April.
Below I have the current code that is pulling up only January. I need the month to be in format "mm". I have run the code without FileMonth = Month(Date - 30) which gave me the previous month number but in single digit format rather than double digit. (for April file it searched for coding as 4 instead of 04). the current code does search for January as 01. As well as if I omit -30 then it will pull May as 05.
Dim Path As String
Dim FileYear As String
Dim FileMonth As String
FileYear = Year(Date - 30)
FileMonth = Format(Month(Date - 30), "mm")
Path = "C:\User\NAME " & FileYear & " " & FileMonth
Workbooks.Open (Path)
The only error is the wrong file being pulled.
Use:
FileMonth = Format((Date - 30), "mm")
Thanks,
Hafeez
EDITED:
Thanks Tony for the heads up! Code is corrected to reflect the comments.
Use:
FileMonth = Format(Format(DateAdd("m", -1, Date), "mm"), "00")
Problem with using 30 days is that not all months have that amount
You could simplify all:
Dim Path As String
Dim FileDate As String
FileDate = Format(DateAdd("m", -1, Date), "yyyy mm")
Path = "C:\User\NAME " & FileDate
Workbooks.Open (Path)
Could any help be offered to try and change the below macro to something more automated. The below macro will filter data in fonction of start and end dates entered manually. I wish to do away with having to enter the dates manually and put a code that allows to filter data 12 months ago. I can't use the inbuilt one year filter in excel because; supposing we're in the middle of the year and i filter for 12 months, it will indeed filter data for the whole of 2018 yet my request will have been to filter 12 months from last month before the actual month we may be in. If i've not been clear enough, i will be happy to be precise for anyone with any idea.
Thank you in advance for any help
This is for excel 2010 vba. I tried to do some reseach but to no avail and any solution makes the code give an error. But am still searching for solutions
Sub filter_()
Sheets("data1 ").Select
MsgBox "12 months filter"
lngStart = Application.InputBox("Enter start date of interest as dd/mm/yyyy", Type:=1 + 2)
lngEnd = Application.InputBox("Enter end date of interest as dd/mm/yyyy", Type:=1 + 2)
Sheets("RBT-RAT ").Select
Range("Tableau1[[#Headers],[Date dernier freinage]]").Select
ActiveSheet.ListObjects("Tableau1").Range.AutoFilter Field:=30, _
Criteria1:=">=" & lngStart, _
Operator:=xlAnd, _
Criteria2:="<=" & lngEnd
End sub
I expect the code to be able to run without manually having to type in the start and end dates within which the filter should be applied and still filter in function of 12 months from which ever time of the year but without applying the filter from the current month. The actual macro posted just below does it but not automatically.
You can use the functions DateAdd and DateSerial.
Imagine today is 2019-01-23. Then …
DateSerial(Year(Date), Month(Date), 1)
… will give you the first day of the current month 2019-01-01. If we then subtract 1 day from that using …
LastDayOfPreviousMonth = DateAdd("d", -1, DateSerial(Year(Date), Month(Date), 1))
… we get the last day of the previous month 2018-12-31 which should be your end date. And if we subtract 12 month from that date …
StartDate = DateAdd("m", -12, LastDayOfPreviousMonth)
… you will get your start date 2017-12-31.
Sub filter_()
MsgBox "12 months filter"
Dim LastDayOfPreviousMonth As Date
LastDayOfPreviousMonth = DateAdd("d", -1, DateSerial(Year(Date), Month(Date), 1))
Dim StartDate As Date
StartDate = DateAdd("m", -12, LastDayOfPreviousMonth)
Sheets("RBT-RAT ").ListObjects("Tableau1").Range.AutoFilter Field:=30, _
Criteria1:=">=" & StartDate, _
Operator:=xlAnd, _
Criteria2:="<=" & LastDayOfPreviousMonth
End Sub
ActiveSheet.ListObjects("Tableau1").Range.AutoFilter Field:=30, _
Criteria1:=">=" & date-365, _
Operator:=xlAnd, _
Criteria2:="<=" & date
Or you can use dateadd("yyyy",-1,date) function to be more precise, change the period you wish to look back on
I got a pretty simple question (but yet I've been stuck at it for some time now). Does anyone know how to make the date value from dd/m/yyyy into dd/mm/yyyy in a variable?
dim lastdaylastmonth as date
lastdaylastmonth = DateSerial(Year(Date), Month(Date), 0)
So this code, as of now, would return the last day of last month, so it will be 31/5/2015. For the sake of formatting, and a MID() down along the code to pull out the month string "05", I will need to convert the date to dd/mm/yyyy or 31/05/2015. Does anyone know the simple solution for this? I've tried:
lastdaylastmonth = format(DateSerial(Year(Date), Month(Date), 0), "dd/mm/yyyy")
and it still returns the same value! Any heroes out there? :D
Use String
Sub dural()
Dim lastdaylastmonth As String
lastdaylastmonth = Format(DateSerial(Year(Date), Month(Date), 0), "dd/mm/yyyy")
MsgBox lastdaylastmonth
End Sub
See this:
lastdaylastmonth = DateSerial(Year(Date), Month(Date), 0)
?lastdaylastmonth
31.05.2015
? format(lastdaylastmonth,"dd.mm.yyyy")
31.05.2015
? format(lastdaylastmonth,"mm")
05
The last output is a string, ready to be used in your code.
I prefer this method simply due to the fact that I have to deal with many different Excel versions around the world. Using format with "mm/dd/yyyy" will only work in the US (or whereever English is the defined language). In other counries the below code will still work.
Dim lastdaylastmonth As Date
'Last day of last month
lastdaylastmonth = Date - Day(Date) - 1
'Formatting it US-style regardless of international Excel or Windows settings
Debug.Print Right("0" & Day(lastdaylastmonth), 2) & "/" & Right("0" & Month(lastdaylastmonth), 2) & "/" & Year(lastdaylastmonth)
I have a column of dates that converted from MS Project into excel as strings.
The format that converted is similar to the following: "March 31, 2014 8:00AM"
I want to convert "March 31, 2014 8:00AM" into type Date but, since it isn't formated MM-DD-YYYY it is not letting me.
Any suggestions?
If the value is in cell A2, for example, you could do the following:
=DATE(YEAR(A2),MONTH(A2),DAY(A2))
For a pure VBA solution, expanding on #cirrusone's suggestion, try this:
Public Sub lime()
Dim dt As Date
' Convert the date string into a Date value.
' Assumes your date string is in cell A1 in the active worksheet of the active
' workbook.
dt = CDate(Cells(1, 1))
' This will print the date with ".." as separators to show that it worked, i.e.
' it should be able to understand every part of the date string passed to it
' after having converted it to a Date value.
MsgBox DatePart("d", dt) & ".." & DatePart("m", dt) & ".." & DatePart("yyyy", dt) & ".." & _
DatePart("h", dt) & ".." & DatePart("n", dt) & ".." & DatePart("s", dt)
End Sub
I put some comments to explain what it's doing. DatePart is a useful function to extract bits of the date (and useful to know in general).