VBA如何:文本框大于当前年份?

时间:2014-02-02 21:01:46

标签: excel vba

大家好,感谢您查看我的问题。

我想在我的用户表单中创建一个按钮,用于检查TextBox_Year中输入的年份是否在2013年和当前年份之间(必须是变量,因此随着时间的推移而变化)。 我一直在网上搜索我的问题的解决方案,但似乎没有任何工作。 下面是我当前的代码,问题是粗体。我还尝试输入Year(date)year(today())但没有运气。

单元格CurrentYear是我的工作簿中包含= Year(today())的命名单元格,并显示2014(这是我想要的值)

再次感谢所有人的帮助!

Private Sub CommandButton_OK_Click()    
If UserForm1.TextBox_Year.Value <= "2012" Then
MsgBox "Please enter a year between 2013 and the year you are in."    
    ElseIf UserForm1.TextBox_Year.Value > **Range("CurrentYear").Value** Then
MsgBox "Please enter a year between 2013 and the year you are in." 
Else:
    UserForm1.Hide  
End If
End Sub

1 个答案:

答案 0 :(得分:1)

试试这段代码:

Private Sub CommandButton_OK_Click()
    Dim textYear As Integer

    On Error GoTo errHandler
    textYear = CInt(UserForm1.TextBox_Year.Value)
    If textYear <= 2012 Then
        MsgBox "Please enter a year between 2013 and the year you are in."
    ElseIf textYear > Range("CurrentYear").Value Then
        MsgBox "Please enter a year between 2013 and the year you are in."
    Else
        UserForm1.Hide
    End If
    Exit Sub
errHandler:
    MsgBox Err.Description
End Sub