2013-11-23 3 views
0

VBA를 사용하는 두 텍스트 상자의 내용을 비교하여 나이를 계산하고 싶습니다.텍스트 상자에서 두 날짜의 차이 찾기

나는 작동하지 않는 많은 코드를 시도했으며, 결국 아래 모듈을 사용했습니다. 사용자 양식에 Excel 시트의 결과가 표시됩니다.

사용자 폼 텍스트 상자를 사용하여 나이를 계산하는 방법을 알고 싶습니다.

모듈 : 사용자 형태로 사용

Function Age(Date1 As Date, Date2 As Date) As String 
    Dim d As Long, m As Long, y As Long 
    If Date2 < Date1 Then 
     Age = "-error-" 
     Exit Function 
    End If 
    m = DateDiff("m", Date1, Date2) 
    d = DateDiff("d", DateAdd("m", m, Date1), Date2) 
    If d < 0 Then 
     m = m - 1 
     d = DateDiff("d", DateAdd("m", m, Date1), Date2) 
    End If 
    y = m \ 12 
    m = m Mod 12 
    If y > 0 Then 
     Age = y & " Year" 
     If y > 1 Then 
      Age = Age & "s" 
     End If 
    End If 
    If Age <> "" And m > 0 Then 
     Age = Age & ", " 
    End If 
    If m > 0 Then 
     Age = Age & m & " Month" 
     If m > 1 Then 
      Age = Age & "s" 
     End If 
    End If 
    If Age <> "" And d > 0 Then 
     Age = Age & ", " 
    End If 

VBA는 다음과 같습니다

Private Sub txtDoB_AfterUpdate() 
    row_number = 0 
    Do 
    DoEvents 

    row_number = row_number + 1 
    item_in_review = Sheets("Data").Range("A" & row_number) 

    If item_in_review = txtSN.Text Then 
     Sheets("Data").Range("B" & row_number) = txtDoB.Text 
     txtAge.Value = Sheets("Data").Range("D" & row_number)  
    End If 

    Loop Until item_in_review = ""  
End Sub 
+0

를' 날짜 1과 날짜 2? 샘플 날짜에 대한 결과로 무엇을 기대하는지 알려주십시오. –

+0

예, 날짜 1은 2009 년 4 월 20 일이고 날짜 2는 2013 년 9 월 15 일입니다. 결과는 4 년 4 개월, 26 일 – user3024687

+0

이어야합니다.이 경우 '2009 년 4 월 20 일'텍스트 또는 날짜'2009-04-20'. 이 날짜에 대한 '연령 기능'의 예상 결과는 무엇입니까? –

답변

0

Date 유형 "제어 2009 년 4 월 20 일,"변환의 문제는 달의 이름 당신의 MonthName(m) 기능 결과 다르다.

Function toDate(strDate As String) As Date 
    Dim i As Integer 
    For i = 1 To 12 
     strDate = Replace(strDate, myMonthName(i), CStr(i)) 
    Next i 
    toDate = CDate(strDate) 
End Function 

' Add other months as your input is 
Function myMonthName(m As Integer) 
    Select Case m 
     Case 1: myMonthName = "January" 
     .. 
     Case 4: myMonthName = "April" 
     .. 
    End Select 
End Function 

을 또한 당신에게 Date들에의 차이를 계산하기 위해이 기능을 제안 할 수 있습니다 :

그럼 당신은 수동으로 처리 할 수있는 당신의 몇 가지 예를 줄 수

Function diffDate(date1 As Date, date2 As Date) As String 
    Dim dTemp As Date 
    dTemp = DateSerial(Year(date1), Month(date1), Day(date1)) - DateSerial(Year(date2), Month(date2), Day(date2)) 
    diffDate = Trim(Year(dTemp) - 1900) & " Year(s), " & Trim(Month(dTemp)) & " Month(s) " & Trim(Day(dTemp)) & " Day(s)" 
End Function