I can't get the current month.
It seems very simple to get the current year and day, as tested with the following:
MsgBox Year(Date)
MsgBox Day(Date)
MsgBox Year(Now)
MsgBox Day(Now)
How is it possible to show the current month as either a number (1, 2 etc.) or a full name?
I could use TODAY() in a cell and convert that in VBA with something like CurrentMonth = MonthName(Month(Sheet1.Range("A1"))) but I would like to do this directly in VBA for Excel.
Try,
debug.print Format(Date, "mmm") 'Mar
debug.print Format(Date, "mmmm") 'March
debug.print Format(Date, "m") '3
debug.print Format(Date, "mm") '03
Month(Now)
Returns the index number associated with the current month.
Jeeped's code below is the most compact, but to give you an idea of how indexes work, the following code will return the month name based on the index returned:
Dim months(11) As String
months(0) = "Jan"
months(1) = "Feb"
months(2) = "Mar"
months(3) = "Apr"
months(4) = "May"
months(5) = "Jun"
months(6) = "Jul"
months(7) = "Aug"
months(8) = "Sep"
months(9) = "Oct"
months(10) = "Nov"
months(11) = "Dec"
Dim nowMonth As Integer
nowMonth = Month(Now)
For i = 0 To 11
If nowMonth = (i + 1) Then
MsgBox (months(i))
End If
Next
Found an easier solution to get the current Month Name
Just use MonthName(Month(Now)) and assign it to a string.
Month(Now) gives you the month number and MonthName() uses that number to display the current month
A really helpful and simple way is to combine the format function together with date.
Examples (assuming today is Oct 23, 2019):
To get current month as a number as in original question:
MsgBox Format(Date, "mm")
^ Will return: 10
To get current month as short text:
MsgBox Format(Date, "mmm")
^ Will return: Oct
To get current month with full text:
MsgBox Format(Date, "mmmm")
^ Will return: October
You can combine these with days and years as well.
Additional examples:
MsgBox Format(Date, "dd-mmm-yyyy")
^ Will return 23-Oct-2019
MsgBox Format(Date, "dddd-mmmm-dd-yyyy")
^ Will return: Wednesday-October-23-2019
This is creating a custom format, so you can rearrange the dd, mm, yyyy areas as you see fit, such as:
MsgBox Format(Date, "yyyy/mm/dd")
^ Will return: 2019/23/10
Here is the best way I have found to do it:
Sub getMonth()
'MsgBox DatePart("m", Date)
'MsgBox Evaluate("MONTH(""" & Date & """)")
'MsgBox VBA.DateTime.Month(Date)
MsgBox Format(Date, "mmmm")
End Sub
Below is how I found the previous month based on the current month name, the assignment to monthNum is the piece needed to solve your question.
month = "February"
'****'
monthNum = Application.Evaluate("=MONTH(1&" & Chr(34) & month & Chr(34) & ")") 'Returns month #
'****'
If monthNum = 1 Then
monthNum = 12
Else
monthNum = monthNum - 1
End If
month = MonthName(monthNum) 'Returns January
Related
I have a date in mm/dd/yyyy format from a textbox in a userform, and I want to get each value mm, dd, and yyyy to a number. (Example, 10/12/2020 would become 2020-10-12)
Here is my code so far, which gets the month part finished.
Dim DateDay As String, DateMonth As String, DateYear As String
Dim firstslash As Integer, secondslash As Integer
firstslash = InStr(TextBox3, "/")
DateMonth = Left(TextBox3, firstslash - 1)
If Len(DateMonth) = 1 Then
DateMonth = "0" & DateMonth
End If
'code for day and year
MsgBox("Date =" & DateYear & "-" & DateMonth & "-" & DateDay)
How can I add to this so it can get the day and year part as well?
The trick is to be sure that you are dealing with a date, that is a large integer (43861 for today). Therefore you should convert whatever is in the textbox to an integer representing a date. That true date you can then present in any format you want. The code below does exactly that.
Private Sub CallExtractDate()
Dim Dat As Date
Dat = ExtractDate("01/31/2020")
MsgBox Format(Dat, "yyyy-mm-dd") & vbCr & _
Format(Dat, "ddd, dd mmm, yyyy") & vbCr & _
Format(Dat, "dddd")
End Sub
Function ExtractDate(ByVal TxtDate As String) As Date
Dim Sp() As String
If IsDate(TxtDate) Then
ExtractDate = CDate(TxtDate)
Else
Sp = Split(TxtDate, "/")
On Error Resume Next
ExtractDate = DateSerial(Int(Sp(2)), Int(Sp(0)), Int(Sp(1)))
End If
End Function
In your project you would probably use the function with a call like this.
Dat = ExtractDate(TextBox1.Value)
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 have a userform where I have two textboxes txtCurrentStatus and txtDCPreviousStatus.
I want the information in txtCurrentStatus to display in txtDCPreviousStatus only if 15 days or more has passed since the last time txtCurrentStatus was last updated.
I have the following code:
Sub txtDCCurrentStatus_AfterUpdate()
dim oldDate as Date
dim timeStamp as String
dim numOfDaysSinceLastUpdated as Integer
'currentRow is the current row that is being updated from another part of my code
oldDate = CDate(Cells(currentRow, 219).Value)
timestamp = "Last updated on " & oldDate & Chr(13) & Chr(13)
numOfDaysSinceLastUpdated = DateDiff("d", oldDate, Date) 'Date is today
If (numOfDaysSinceLastUpdated > 15) Then
Me.txtDCPreviousStatus.Value = timestamp & Me.txtDCPreviousStatus.Value
Me.txtDCPreviousStatus.Value = Me.txtDCCurrentStatus.Value & _
Chr(13) & Me.txtDCPreviousStatus.Value
Else
'Do nothing
End If
Cells(currentRow, 219).Value = Format(Now, "mm-dd-yyyy")
End Sub
I am having two issues:
1) If the Cells(currentRow, 219).Value = ""because txtDCCurrentStatus was never updated then I get a message
Run-Time error '6': Overflow
at numOfDaysSinceLastUpdated = DateDiff("d", oldDate, Date)
2) To solved this issue, I moved Cells(currentRow, 219).Value = Format(Now, "mm-dd-yyyy") at the very top. When I do that the text never move to txtDCPreviousStatus because the date changes automatically to today the moment I make a change so it's never more than 15 days.
Basically, I am:
Putting into oldDate, the date txtDCCurrentStatus was last updated
Checking if 15 days has passed since txtDCCurrentStatus was updated by doing oldDate - Date then putting it in numOfDaysSinceLastUpdated
If yes, I then move the content of txtDCCurrentStatus to txtDCPreviousStatus
Save now the new Date that txtDCCurrentStatus is being updated to Cells(currentRow, 219).Value = Format(Now, "mm-dd-yyyy")
Is there a way I can fix these two issues?
Thanks to #ScottHoltzman answer. I fixed my issue
I added the following at the beginning of my Sub and it worked
if oldDate = Empty then
Me.txtDCPreviousStatus.Value = ""
Else ...
The issue I was having was that at first I was checking if oldDate = "". Even if oldDate is empty, oldDate is a Date and when it's empty, it print as "12:00:00 AM" and "" <> "12:00:00 AM" so I had to check if it was empty
I have a cell with a date:
30/04/1991
I need to make a compare with today's date, but with day and month of that cell, but with current year. But it isn't working.
I have the following:
MsgBox Format(Day(cell.Value) & "/" & Month(cell.Value) & "/" & Year(Now), "dd/mm/yyyy") < Format(Now, "dd/mm/yyyy")
The result is "30/04/2017 < 01/05/2017"
But msgbox result is "False". Which is wrong, given today's date as "01/05/2017"
What am I doing wrong?
To avoid issues with February 29th, you can compare just the month and date:
MsgBox Format(cell, "mmdd") < Format(Now, "mmdd")
Update
DatePart("y", Date) can be used to get the Day of year:
MsgBox DatePart("y", cell) < DatePart("y", Now)
Debug.Print DatePart("y", "2 28") // 59
Debug.Print DatePart("y", "2 29 16") // 60
I would recommend using DateDiff fuinction.
You can use Date instead of Now since you only need the date, and not the time.
If you use DateDiff you can keep the 2 values as Date variable, and instead of using DateValue with some & and "/", you can have a shorter and cleaner version DateSerial(Year(Date), Month(cell.Value), Day(cell.Value)).
Code:
MsgBox DateDiff("d", DateSerial(Year(Date), Month(cell.Value), Day(cell.Value)), Date) > 1
If you want to get also the number of days between these 2 dates:
MsgBox DateDiff("d", DateSerial(Year(Date), Month(cell.Value), Day(cell.Value)), Date)
I solved by myself with
MsgBox DateValue(Day(cell.Value) & "/" & Month(cell.Value) & "/" & Year(Now)) < DateValue(Date)
How to pass the MS Access table column value in MS Excel 2010 Workday function in range list of holidays.
I have following table.
date_val
9/23/2016
9/24/2016
I want to use above list of dates in MS Excel 2010 Workday function in list of Holidays.
Example Workday(Today,addition of no of days, exclusion of Holidays)
As per above syntax of Workday function, I am looking
Workdays(Any Date, addition of one day, Exclude above listed MS Access Table column dates).
Can anyone assist how to pass MS Access Table column date value in holiday_array in Workday function?
Note : Code needs to implement in MS Access VBA environment.
As long as you pass an array to the Excel function you can call it from Access VBA.
General usage of function described here
Subroutine with Two examples
Public Sub TestWorkdayFunction()
Dim xlApp As Excel.Application
Dim startDate As Date
Dim numDays As Long
Dim arrDates As Variant
Dim nextDate As Date
Dim strDates As String
' Array of Holidays
arrDates = Array("1/1/2016", "3/25/2016", "3/28/2016")
Set xlApp = CreateObject("Excel.Application")
Debug.Print "Loading Array of Holidays From Preset List"
startDate = #12/30/2015#
Debug.Print startDate
numDays = 1
nextDate = xlApp.WorksheetFunction.WorkDay(startDate, numDays, arrDates)
Debug.Print "Next Work Day after " & numDays & ": " & Format(nextDate, "Long Date")
numDays = 2
nextDate = xlApp.WorksheetFunction.WorkDay(startDate, numDays, arrDates)
Debug.Print "Next Work Day after " & numDays & ": " & Format(nextDate, "Long Date")
Debug.Print "Loading Array of Holidays From Recordset"
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT date_val FROM Table2", dbOpenSnapshot, dbReadOnly)
With rs
While Not .EOF
' Build comma separated list of dates (in Serial Date format)
' You could build date list with text format, enclosing in double quotes
strDates = strDates & DateSerial(Year(!date_val), Month(!date_val), Day(!date_val)) & ","
.MoveNext
Wend
.Close
End With
startDate = #3/24/2016#
Debug.Print startDate
' Remove Last comma
strDates = Left$(strDates, Len(strDates) - 1)
' Build Array of Holiday Dates
arrDates = Split(strDates, ",")
numDays = 1
nextDate = xlApp.WorksheetFunction.WorkDay(startDate, numDays, arrDates)
Debug.Print "Next Work Day after " & numDays & ": " & Format(nextDate, "Long Date")
numDays = 5
nextDate = xlApp.WorksheetFunction.WorkDay(startDate, numDays, arrDates)
Debug.Print "Next Work Day after " & numDays & ": " & Format(nextDate, "Long Date")
Set rs = Nothing
Set xlApp = Nothing
End Sub
Actual Debug Output
Loading Array of Holidays From Preset List
12/30/2015
Next Work Day after 1: Thursday, December 31, 2015
Next Work Day after 2: Monday, January 04, 2016
Loading Array of Holidays From Recordset
3/24/2016
Next Work Day after 1: Tuesday, March 29, 2016
Next Work Day after 5: Monday, April 04, 2016