VBA Macro and changing date format to mmm-yy - vba

I am having problems with an excel macro (VBA) that is meant to grab a date from an excel spreadsheet, subtract one month and reformat it to MMM-YY. Basically I want to take 3/31/2013 and convert it to Feb-13
Here is my code:
Dim ReportDate As Date
ReportDate = Worksheets("Current").Cells(2, 16) 'ex. 03-31-2013
prevMonth = Format((Month(ReportDate) - 1) & "/" & Day(ReportDate) & "/" & Year(ReportDate), "mmm") & "-" & Format(ReportDate, "yy")
Debug.Print prevMonth
The result I get is 2/31/2013-13
So I tried changing the prevMonth variable:
prevMonth = Format((Month(ReportDate) - 1) & "/" & Day(ReportDate) & "/" & Year(ReportDate), "mmm-yy")
But got just 2/31/2013 again
I tried to declare prevMonth as an Integer or a Date but I get a type mismatch error. I can only declare it as a String but it still doesn't help the program.
Thanks in advance for your help.

Try this
Sub Demo()
Dim ReportDate As Date
Dim prevMonth As Date
ReportDate = Worksheets("Current").Cells(2, 16) 'ex. 03-31-2013
prevMonth = DateAdd("m", -1, ReportDate)
Debug.Print Format(prevMonth, "mmm-yy")
End Sub

Related

Opening Files in file path but being able to change the date on new workdays

I open multiple files at my job and would like to know how to open different files by concatenating a workday variable into the file path. Is this possible?
Code:
Sub File_Demo()
Dim pathname
Dim Date_X
Dim Date_Y
Date_X = “02.01.22”
Date_Y = 20220201
Pathname =
“C:\Users\Jinx\Desktop\PDF_Files\2022\Feb\& Date_X &\PDF_FileName & Date_Y &.pdf”
ActiveWorkbook.FollowHyperlink pathname
End Sub
I would use this code to open multiple files at once by using a workday - 1, -2, -3, etc type of variable but am stuck on where to start in this process.
The Date Keyword can be used in VBA to get the current date value. The Format function can then turn the date value into whatever format you supply. On that article I linked above, they give a useful chart of how to create a date format.
Format(Date, "mm.dd.yy") would be "02.18.22" today and "02.19.22" tomorrow.
Format(Date, "yymmdd") would be "220218" today and "220219" tomorrow.
If you need pieces of the current date, like the Year or the Month you can use the aptly named Year and Month functions. Year(Date) would return 2022. And Month(Date) would return 2. If you need the month as a three-letter abbreviation, Format(Date, "mmm") would give you "Feb".
So for your file path you can do:
Pathname = "C:\Users\Jinx\Desktop\PDF_Files\" & Year(Date) & "\" & Format(Date, "mmm") & "\" & Format(Date, "mm.dd.yy") & "\PDF_FileName" & Format(Date, "yymmdd") & ".pdf"
If you need to change the date, and re-build the pathname, simply replace Date with a different value. You can even have a loop like
'From yesterday to three days from now
For myDate = Date - 1 to Date + 3
Pathname = "C:\Users\Jinx\Desktop\PDF_Files\" & Year(myDate) & "\" & Format(myDate, "mmm") & "\" & Format(myDate, "mm.dd.yy") & "\PDF_FileName" & Format(myDate, "yymmdd") & ".pdf"
'Do Stuff
Next
Notes: I also noticed that the quotation marks in your post were not standard " marks. That will cause an error in VBA since they will register as unrecognized symbols. Additionally, strings must be concatenated with & symbols, but those must be outside the quotation marks.
Eg. myString = "abc" & "def"
NOT myString = "abc&" "def"

textBox to Date MS Access

Please have at look on my issue.
Background data: ItemB - field with date type, which has YYMMDDHHNN format
inptdate - textBox for input data in YYMMDDHHNN format
What needed, transform data from String format (inptdate) into Date format(ItemB)
My way
Private Sub Idate_AfterUpdate()
Dim mydate As String
mydate = "2212131400"
inptdate= mydate
Me.ItemB = CDate(Mid(mydate, 6, 2) & "," & Mid(mydate, 4, 2) & "," & Mid(mydate, 2, 2) & " " & Mid(mydate, 8, 2) & ":" & Mid(mydate, 10, 2))
End Sub
but my code execute with an "Type mismatch" error
You can use Format and CDate:
Dim TrueDate As Date
mydate = "2212131400"
TrueDate = CDate("20" & Format(mydate, "##\/##\/## ##\:##"))

VBA, Dynamically pickup a date

I have a file I want to pickup from the previous wednesday June 10th. I will be running my code today (Sunday June 14th). However this will reoccur every week.
Is there a way I can make my code dynamic enough to pickup the previous wednesday date?
Here is my code Set wbTarget = Workbooks.Open("C:\extract\Business_Report_20200527.xlsx")
Can I alter that path to dynamically pickup a date?
Thank you.
Try this:
Dim today As Date
Dim IntervalType As String
Dim FilePath As String
today = Date()
IntervalType = "d"
While Weekday(today) <> vbWednesday
today = DateAdd(IntervalType, -1, today)
Wend
FilePath = "C:\extract\Business_Report_" + Format(today, "yyyymmdd") + ".xlsx"
Set wbTarget = Workbooks.Open(FilePath)
Another way to do it:
Sub Test()
MsgBox "Last Wednesday: " & PreviousWednesday & vbCr & _
"Wednesday prior to 9th June: " & PreviousWednesday(DateValue("9 June 2020")) & vbCr & _
"Last Wednesday formatted: " & Format(PreviousWednesday, "yyyymmdd")
'Your code:
'Set wbTarget = Workbooks.Open("C:\extract\Business_Report_" & Format(PreviousWednesday, "yyyymmdd") & ".xlsx")
End Sub
Public Function PreviousWednesday(Optional CurrentDate As Date) As Date
If CurrentDate = 0 Then CurrentDate = Date
PreviousWednesday = (CurrentDate - Weekday(CurrentDate, vbMonday) + 1) - 5
End Function

Access VBA not appending date properly in loop

I'm trying to make a loop that (among other things) inserts a date and then in each row, adds a month to that date. It is not appending the first date properly. The date is a DLookup from a date field in a query, so I think it should work as a date. And I don't see anything wrong with my SQL statement. But when this runs the date shows up in the table as 12/30/1899 and if you click on it, it changes to 12:03:34 AM. It's supposed to be 5/1/15. Nothing I've tried to get this to work has given me any other results.
Here's my code, please note: there's probably a couple other things wrong with my overall code I'm sure, but I'm focusing on this date problem for now. Feel free to point out whatever you find, though.
Private Sub AmortButton_Click()
DoCmd.SetWarnings False
Dim Account As Long: Account = DLookup("[L#]", "qry_info4amort") 'working
Dim StartDate As Date: StartDate = CDate(DLookup("PaidToDate", "qry_info4amort")) 'NOT WORKING
Dim InterestRate As Double: InterestRate = DLookup("IntCur", "qry_info4amort") 'working
Dim piConstant As Integer: piConstant = DLookup("[P&IConstant]", "qry_info4amort")
Dim UPB As Currency: UPB = DLookup("UPB", "qry_info4amort") 'working
Dim tempUPB As Currency: tempUPB = UPB 'working (just to establish variable)
Dim AmortInterest As Currency: AmortInterest = 0 'working (just to establish variable)
Dim AmortPrincipal As Currency: AmortPrincipal = 0 'working (just to establish variable)
Dim Ranking As Integer: Ranking = 1 'working (just to establish variable)
Dim PaymentLoop As Integer: PaymentLoop = 1 'working (just to establish variable)
Dim PaymentNumber As Integer: PaymentNumber = DLookup("NumPmts", "qry_info4amort") 'working
Dim tempInterest As Integer: tempInterest = 0 'working (just to establish variable)
Do While PaymentLoop <= PaymentNumber 'working
tempInterest = Round(tempUPB * (InterestRate / 12), 2)
tempUPB = Round(tempUPB - (piConstant - tempInterest), 2)
AmortPrincipal = AmortPrincipal + (piConstant - tempInterest)
AmortPrincipal = (piConstant - tempInterest)
AmortInterest = AmortInterest + tempInterest
DoCmd.RunSQL "INSERT INTO tbl_AmortizationTest ([L#],[Payment#],[PaymentDate],[UPB],[Interest],[Principal],[TotalPayment],[InterestRate],[TempUPB],[Ranking]) " & _
"VALUES (" & Account & "," & PaymentLoop & "," & StartDate & "," & UPB & "," & tempInterest & "," & AmortPrincipal & "," & (tempInterest + AmortPrincipal) & "," & InterestRate & "," & tempUPB & "," & Ranking & ")"
UPB = tempUPB
StartDate = DateAdd("m", 1, StartDate) 'NOT WORKING
PaymentLoop = PaymentLoop + 1 'working
Ranking = Ranking + 1 'working
Loop
MsgBox "Done!"
DoCmd.SetWarnings True
End Sub
First, if PaidToDate is of data type Date, retrieve your date as is:
StartDate = DLookup("PaidToDate", "qry_info4amort")
If it is a string, CDate or DateValue will do:
StartDate = DateValue(DLookup("PaidToDate", "qry_info4amort"))
Second, format a proper string expression for the date when concatenating it into SQL:
... PaymentLoop & ",#" & Format(StartDate, "yyyy\/mm\/dd") & "#," & UPB ...
Instead of using CDate() around your DLookup("PaidToDate", "qry_info4amort") you are probably going to have to pull out the relevant parts piece by piece...
StartDate = DateSerial(<year>, <month>, <day>)
For example, if DLookup("PaidToDate", "qry_info4amort") returns 05012015 then you could do:
StartDate = DateSerial(Mid(DLookup("PaidToDate", "qry_info4amort"),5,4), Left(DLookup("PaidToDate", "qry_info4amort"),2), Mid(DLookup("PaidToDate", "qry_info4amort"),3,2))
If the DLookup("PaidToDate", "qry_info4amort") returns a value with / in it, then you will have to use some Instr() functions... More on that here.

VBA generating formula via variables

Can someone please help me to fix the formula in the sub. I need to enter dates into it via variables but it always gives me an error '13' data types
I'm talking about the bit:
Cells(5, field).FormulaLocal = "=SUMMEWENNS(Rawdata!K2:K3446;Rawdata!I2:I3446;""bezahlt"";Rawdata!A2:A3446;" >= " & weekstart & "";Rawdata!A2:A3446;" <= " & weekend & "")"
The Sub apart from that formula works.....
Sub get_cal_weeks()
Dim weeks As Integer, i As Integer, col As String, weekstart As Date, weekend As Date, calweeks() As Variant
'start column is D
col = "D"
'get amount of weeks
weeks = countcalweeks()
'populate array calweeks
calweeks = fillcalweeks(weeks)
For i = 0 To weeks
field = i + i + 4
weekstart = calweeks(i, 0)
weekend = calweeks(i, 1)
Cells(5, field).FormulaLocal = "=SUMMEWENNS(Rawdata!K2:K3446;Rawdata!I2:I3446;""bezahlt"";Rawdata!A2:A3446;" >= " & weekstart & "";Rawdata!A2:A3446;" <= " & weekend & "")"
Next
End Sub
Thank you
I suggest you convert to long (or double if you need times)
Cells(5, field).FormulaLocal = "=SUMMEWENNS(Rawdata!K2:K3446;Rawdata!I2:I3446;""bezahlt"";Rawdata!A2:A3446;"">=" & CLng(weekstart) & """;Rawdata!A2:A3446;""<=" & CLng(weekend) & """)"