Previous Month Recall formatting - excel

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)

Related

I want to get the file on directory counting 21 previous days from today

I have a directory with subdirectories that contains monthly files archived.
I want to get the data from files from subdirectory counting 21 previous days from today and if is not in my current subdirectory, then skip to previous subdirectory.
The way I declared, brings me the content that I need, however with exactly the currently month, number corresponding of month, and year.
Sub getNumber(CM As String, shift As String, fileDate As String)
Dim newDate: newDate = Format(DateAdd("M", 0, Now), "MM-MMMM")
filePath ="\\bt\depthr\cement\trailer\Plans\Day Shift\05-May\trailer_flow_5-5-22 Day Shift Plan.xlsb\" & newDate & "\"
fileName = CM & "_" & "flow" & "_" & fileDate & "Plans" & ".xlsb"```
How can I correct it to bring me previous 21 days and skip to previous subdirectory if the 21 days includes previous month?
Thank you.
This will give you 21 days back date in VBA.
Dim newD As Date
newD = Date - 21
MsgBox newD

Create a folder name with year and two digit month

I'm trying to create a folder with a the year and month of my choosing. My issue is that the month name (in this case January) keeps appearing as 1 instead of 01. I've tried several variations of the Format function everywhere in my code but I still get 1 returned. See below for code
Sub CreateFolder()
Dim sMonthName As String
Dim iMonthNumber As Integer
sMonthName = ThisWorkbook.Worksheets("Overview").Range("C2")
iMonthNumber = Month(DateValue("01-" & sMonthName & "-1900"))
MkDir "FILE PATH" & ThisWorkbook.Worksheets("Overview").Range("C3") & "." & iMonthNumber
End Sub
Cell C2 in the Overview Tab is where I have the month name, while cell C3 in the same tab is where I have the year. Is there a way to return the month as two digits? Let me know if you need any more information
Thank you.
You can simplify a bit by creating a date containing both the month and year, and then using Format$:
With ThisWorkbook.Worksheets("Overview")
Dim dt As Date
dt = DateValue("01-" & .Range("C2").Value & "-" & .Range("C3").Value)
End With
MkDir "FILE PATH" & Format$(dt, "yyyy.mm")

Day(Now) displaying January, 1900?

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.

Finetuning how the date is displayed after adding it to a cell

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")

Date formatting - making dd/m/yyyy into dd/mm/yyyy

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)

Resources