VBA Excel-使用验证设置年份范围的格式

VBA Excel-使用验证设置年份范围的格式,excel,vba,Excel,Vba,只是想问一下是否可以在文本框中输入年份范围?我的想法是,当用户键入前4个数字时,它会自动显示下一年的破折号和年份。例如,当用户在文本框中或第四个数字之后键入2020时,-2021将自动显示 这是我一直在研究的最新代码 If KeyAscii >= 48 And KeyAscii <= 57 Then If Len(tb.Text) = 9 Then KeyAscii = 0 If tb.SelStart = 0 Then

只是想问一下是否可以在文本框中输入年份范围?我的想法是,当用户键入前4个数字时,它会自动显示下一年的破折号和年份。例如,当用户在文本框中或第四个数字之后键入
2020
时,
-2021
将自动显示

这是我一直在研究的最新代码

If KeyAscii >= 48 And KeyAscii <= 57 Then
   If Len(tb.Text) = 9 Then KeyAscii = 0               
      If tb.SelStart = 0 Then
           If KeyAscii < 49 Or KeyAscii > 50 Then KeyAscii = 0
           ElseIf tb.SelStart = 4 Or tb.SelStart = 5 Then
               If KeyAscii < 49 Or KeyAscii > 51 Then
                  KeyAscii = 0
               Else
                  tb.Text = Left(tb.Text, 4) & "-" & CInt(tb.Text + 1)
               End If
           End If
Else
    KeyAscii = 0
End If
如果KeyAscii>=48和KeyAscii=50,则KeyAscii=0
ElseIf tb.SelStart=4或tb.SelStart=5,则
如果KeyAscii<49或KeyAscii>51,则
KeyAscii=0
其他的
tb.Text=Left(tb.Text,4)&“-”和CInt(tb.Text+1)
如果结束
如果结束
其他的
KeyAscii=0
如果结束
更新:现在显示
-2021
,但问题是我需要在
-2021
出现之前先输入第5个数字。另外,我输入的第五个数字出现在值的最后部分


例如,我在文本框中输入
2020
。我需要再输入一个数字,以便显示
-2021
,然后该值变为
2020-20213
3
是我在出现
-2021
之前输入的数字。

一个选项是使用文本框的
Change
事件响应用户输入。在下面的代码中,当输入的长度为4个字符时,如果输入是一个数字,它会自动添加“-”和下一年。它还选择下一年,以便用户可以轻松覆盖默认值

这有用吗

Private Sub TextBox1_Change()
    Dim sInput As String
    
    sInput = TextBox1.Value
    
    If Len(sInput) <> 4 Then
        Exit Sub
    End If
    
    If IsNumeric(sInput) Then
        TextBox1.Value = sInput & "-" & (CInt(sInput) + 1)
        TextBox1.SelStart = 5
        TextBox1.SelLength = 4
    End If
End Sub
Private子文本框1_Change()
作为字符串的单音字
sInput=TextBox1.Value
如果Len(sInput)4那么
出口接头
如果结束
如果是数字(sInput),则
TextBox1.Value=sInput&“-”和(CInt(sInput)+1)
TextBox1.SelStart=5
TextBox1.SelLength=4
如果结束
端接头

以下是我提出的解决方案

tb.MaxLength = 9     
If KeyAscii >= 48 And KeyAscii <= 57 Then 'This textbox only allows for numbers 0-9
  If Len(tb.Text) = 9 Then KeyAscii = 0        
     If tb.SelStart = 0 Then
       If KeyAscii < 49 Or KeyAscii > 50 Then KeyAscii = 0     
          ElseIf tb.SelStart = 4 Then
          If KeyAscii < 49 Or KeyAscii > 51 Then
               KeyAscii = 0
          Else
              tb.Text = Left(tb.Text, 4) & "-" & CInt(tb.Text + 1)
          End If
        End If
Else
   KeyAscii = 0
End If
tb.MaxLength=9

如果keyscii>=48和keyscii,我需要验证多个文本框,这就是我使用
文件的原因。我在我的代码中使用了这个
sInput&“-”&(CInt(sInput)+1)
,它很有帮助,但我仍然有一个问题。当我输入第五个数字时,值变成了
2020-20212
。最后一个值中的2是我在出现
2021
之前输入的值。