Excel 用户表单 - 检查单元格是否为空

Excel Userform - check if cell is empty then

我正在尝试制作一个用户表单,在用户点击按钮后,它首先检查指定的单元格是否为空。

如果它们已经有值,那么我想向用户显示一个消息框。如果它们是空的,那么我将继续填写它们。出于某种原因,每当我 运行 用户表单时,它都会显示单元格不为空的消息框,但无论如何都会继续填写它们。我不确定我是否错误地使用了 if 语句或其他什么。

这是我从用户窗体文本框输入中声明变量 (BtwCells) 后开始的代码:

If IsEmpty(BtwCells.Value) = False Then

MsgBox ("Error - overlapping reservations")

End If

BtwCells.Interior.ColorIndex = 6
BtwCells.Value = Application.username & "/" & Me.TBNotes.Value
End Sub

根据您的代码原样 - 您的 If...Then 语句存在逻辑错误。

语句被执行,不管你的MsgBox是否显示,代码会继续:

BtwCells.Interior.ColorIndex = 6
BtwCells.Value = Application.username & "/" & Me.TBNotes.Value

您需要将 If...Then 块中的代码告知 Exit Sub,这将中止代码并阻止执行该行以下的任何内容。

If IsEmpty(BtwCells.Value) = False Then

    MsgBox ("Error - overlapping reservations")
    Exit Sub  'This will abort the code below this line from executing.

End If

BtwCells.Interior.ColorIndex = 6
BtwCells.Value = Application.username & "/" & Me.TBNotes.Value
End Sub