我正在尝试创建一个VBA函数,该函数返回带有单元格引用的月份数。我想调用函数CheckMonth
例如,如果我将01/01/2019(dd / mm / yyyy)作为日期,而不是我想将其返回为整数(在本例中为01)
或对于04/06/2019(返回06) 12/09/2019(返回09)等等
Function CheckMonth () As integer
Mid(Range("Active.cell"), 4, 2)
我知道我需要使用此Mid(range(x,4,2)),但不确定如何实现。
请您告知我该怎么做?
答案 0 :(得分:3)
如果您需要VBA,请考虑:
Function CheckMonth(r As Range) As Integer
CheckMonth = Month(r.Value)
End Function
无论日期格式如何,它都会返回月份号。
答案 1 :(得分:1)
根据以前的注释,您可以使用月份功能。您还需要添加Excel.Range参数:
Function CheckMonth(rngCell As Excel.Range) As Integer
CheckMonth = Month(rngCell.Value)
End Function
答案 2 :(得分:0)
从学习的角度来看,也许有一些选择可以使您更好地了解可用的各种工具:
Public Function CheckMonth(r As Range) As String
' Find month number and then format that to double-digit string
CheckMonth = Format(Month(r.Value), "00")
End Function
Public Function CheckMonth2(r As Range) As String
' Format the date to 'mm' - i.e. just the month element
CheckMonth2 = Format(r.Value, "mm")
End Function
Public Function CheckMonth3(r As Range) As String
' Format the date to a standard string and extract the middle element
CheckMonth3 = Mid(Format(r.Value, "dd/mm/yyyy"), 4, 2)
End Function
Public Function CheckMonth4(r As Range) As String
' Concatenate a zero with the month number, then take last 2 characters
CheckMonth4 = Right("0" & Month(r.Value), 2)
End Function