首页 > 解决方案 > InputBox 数据验证和结束循环

问题描述

我有一些代码可以通过InputBox(见下文)输入日期。问题是它Else不起作用(即,如果用户输入的格式不是 mm/dd/yy 它不会停止)。如何使用户必须以呈现的格式输入它?

另外,我想用endDate. 现在,如果您输入 01/10/20 作为开始日期并输入 12/31/20 作为结束日期,它将在 2021 年 1 月 1 日停止。如何让它在 2020 年 12 月 31 日停止?

  Dim startDate As Date
  Dim endDate As Date

  startDate = InputBox("Enter project start date in format mm/dd/yy", "User date", Format(Now(), "dd/mm/yy"))
  endDate = InputBox("Enter project end date in format mm/dd/yy", "User date", Format(Now(), "dd/mm/yy"))

  If IsDate(startDate) Then
    startDate = Format(CDate(startDate), "mmm d, yyyy")
  Else
    MsgBox "Wrong date format"
  End If

  If IsDate(endDate) Then
    endDate = Format(CDate(endDate), "mmm d, yyyy")
  Else
    MsgBox "Wrong date format"
  End If

Range("A2").Value = startDate

Dim i As Long
Dim j As Long
Dim x As Integer

i = startDate
j = endDate
x = 3

Do Until i >= j
    Cells(x, 1).Value = i + 7
    i = i + 7
    x = x + 1
Loop

End Sub```

标签: excelvba

解决方案


当日期不正确时,它会显示消息框,但在关闭消息框后没有任何东西可以阻止它继续执行代码。有几种方法可以解决此问题。

首先是简单地添加行

Exit Sub

在显示 msgbox 之后。

但是,我假设您不希望程序在输入错误后放弃。相反,您可能希望它通知用户它是不正确的并要求另一个输入,直到他们提供有效的格式。

我通常这样做的方式是使用 Do Until 循环。尝试这个:

  startDate = InputBox("Enter project start date in format mm/dd/yy", "User date", 
  Format(Now(), "dd/mm/yy"))

  Do Until IsDate(startDate)
    MsgBox "Wrong date format."
    startDate = InputBox("Enter project start date in format mm/dd/yy", "User date", 
  Loop

  endDate = InputBox("Enter project end date in format mm/dd/yy", "User date", 
  Format(Now(), "dd/mm/yy"))

  Do Until IsDate(endDate)
    MsgBox "Wrong date format."
    startDate = InputBox("Enter project start date in format mm/dd/yy", "User date", 
  Loop

第二个问题是因为您在添加 7之前检查 i 的值。另外,仅当 endDate 与 startDate 相差 7 的倍数时才会打印。如果您总是希望打印结束日期,则必须进行一些更改。

试试这个:

i = startDate + 7
j = endDate
x = 3

Do Until i > j
    Cells(x, 1).Value = i
    i = i + 7
    x = x + 1
Loop

Cells(x, 1).Value = endDate


推荐阅读