从文本框中找出两个日期的差异

时间:2013-11-23 11:01:55

标签: excel-vba vba excel

我想通过使用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

1 个答案:

答案 0 :(得分:0)

将“2009年4月20日”转换为Date类型的问题是您的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 s的差异:

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