Excel:validation数据不会强制用户input“date格式”数据

我在使用Excel数据validation时遇到了问题,因为它不会强制用户在单元格中inputdatetypes的数据。 我正在创build一个表单,允许从多个纸张表单中input数据。

问题是,如果用户在Date单元格中input“41000”,它将接受数据为自1/1/1901以来的天数(不知道它是否是绝对的,这对我来说是validation条件)。

我想知道是否有一个解决scheme,防止用户input任何其他比XX / XX / XXXXdate。

谢谢一堆。

SV

这只是一个使用单元格A1A10的例子

你可以适应你的具体布局。

A1A10中的单元格必须先格式化为文本。 然后在工作表区域中安装以下事件macros:

Private Sub Worksheet_Change(ByVal Target As Range) Dim rng As Range, r As Range, v As String, inty As Range Dim d As Integer, m As Integer, y As Integer Set rng = Range("A1:A10") Set inty = Intersect(rng, Target) If inty Is Nothing Then Exit Sub On Error GoTo NotGood For Each r In inty v = r.Text ary = Split(v, "/") If UBound(ary) <> 2 Then GoTo NotGood d = CInt(ary(0)) m = CInt(ary(1)) y = CInt(ary(2)) If y > 9999 Then GoTo NotGood If y < 1900 Then GoTo NotGood If m > 12 Then GoTo NotGood If d > 31 Then GoTo NotGood GoTo nxtr NotGood: MsgBox "bad input in cell " & r.Address(0, 0) Application.EnableEvents = False Application.Undo Application.EnableEvents = True On Error GoTo 0 Exit Sub nxtr: Application.EnableEvents = False r.ClearContents r.NumberFormat = "dd/mm/yyyy" r.Value = DateSerial(y, m, d) Application.EnableEvents = True Next r End Sub 

这个macros就像数据validation一样。 它testing一些常见的错误,并拒绝它们。

因为它是工作表代码,所以安装和自动使用非常简单:

  1. 右键单击Excel窗口底部附近的选项卡名称
  2. select查看代码 – 这会popup一个VBE窗口
  3. 粘贴东西,closuresVBE窗口

如果您有任何疑问,请先在试用工作表上尝试。

如果您保存该工作簿,该macros将与它一起保存。 如果您在2003年以后使用的是Excel版本,则必须将该文件另存为.xlsm而不是.xlsx

要删除macros:

  1. 调出上面的VBE窗口
  2. 清除代码
  3. closuresVBE窗口

要了解有关macros的更多信息,请参阅:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

要了解有关事件macros(工作表代码)的更多信息,请参阅:

http://www.mvps.org/dmcritchie/excel/event.htm

macros必须启用这个工作!