'DATEDIF関数と同機能のユーザ定義関数 '機能およびパラメータはDATEDIFワークシート関数とほぼ同じです。 'date1およびdate2には、日付の表示形式を設定したセルの値、または '日付を表す文字列(1900年以前の日付も可能)が指定できます。 'ただし、数値や計算結果は指定できません。 '日付計算の結果は文字列に変換して指定してください。 '例 =MyDateDif(TEXT(A1+1,"yyyy/m/d"),B1,"ymd") 'intervalに"ymd"を指定すると、年*10000+月*100+日を返します。 Option Explicit Function MyDateDif(date1 As Variant, date2 As Variant, _ interval As String) As Variant Dim startDate As Date, endDate As Date Dim y As Integer, m As Integer, d As Integer Select Case VarType(date1) Case vbDate startDate = date1 Case vbString If IsDate(date1) Then startDate = CDate(date1) Else MyDateDif = CVErr(xlErrValue) Exit Function End If Case Else MyDateDif = CVErr(xlErrValue) Exit Function End Select Select Case VarType(date2) Case vbDate endDate = date2 Case vbString If IsDate(date2) Then endDate = CDate(date2) Else MyDateDif = CVErr(xlErrValue) Exit Function End If Case Else MyDateDif = CVErr(xlErrValue) Exit Function End Select If startDate > endDate Then MyDateDif = CVErr(xlErrNum) Exit Function End If Select Case UCase(interval) Case "Y" y = Year(endDate) - Year(startDate) m = Month(endDate) - Month(startDate) d = Day(endDate) - Day(startDate) If d < 0 Then m = m - 1 If m < 0 Then y = y - 1 MyDateDif = y Case "M" y = Year(endDate) - Year(startDate) m = Month(endDate) - Month(startDate) d = Day(endDate) - Day(startDate) If d < 0 Then m = m - 1 MyDateDif = y * 12 + m Case "D" MyDateDif = endDate - startDate Case "MD" d = Day(endDate) - Day(startDate) If d < 0 Then d = Day(endDate - Day(endDate)) - Day(startDate) If d < 0 Then d = Day(endDate) Else d = d + Day(endDate) End If MyDateDif = d Case "YM" m = Month(endDate) - Month(startDate) d = Day(endDate) - Day(startDate) If d < 0 Then m = m - 1 If m < 0 Then m = m + 12 MyDateDif = m Case "YD" If DateSerial(Year(endDate), Month(startDate), Day(startDate)) _ > endDate Then MyDateDif = endDate - _ DateSerial(Year(endDate) - 1, Month(startDate), Day(startDate)) Else MyDateDif = endDate - _ DateSerial(Year(endDate), Month(startDate), Day(startDate)) End If Case "YMD" y = Year(endDate) - Year(startDate) m = Month(endDate) - Month(startDate) d = Day(endDate) - Day(startDate) If d < 0 Then d = Day(endDate - Day(endDate)) - Day(startDate) If d < 0 Then d = Day(endDate) Else d = d + Day(endDate) m = m - 1 End If If m < 0 Then m = m + 12 y = y - 1 End If MyDateDif = CLng(y) * 10000 + m * 100 + d Case Else MyDateDif = CVErr(xlErrNum) End Select End Function