Excel VBA 用于检查单元格值是否出现在其他单元格数组中的脚本。如果不是,则显示 MsgBox 并强制用户重新输入

Excel VBA script to check whether cell value appears in array of other cells. If not, show a MsgBox and force the user to re-input

VBA 初学者。对于无法提供代码片段,我深表歉意,但我正在寻找一个按如下方式工作的脚本:

  1. 检查单元格(比如 A1)中输入的值是否出现在单元格数组(比如 B1:B100)中。
  2. 如果输入到 A1 的值没有出现在 B1:B100 中,显示带有 Retry/Cancel 按钮的消息框,警告用户他们的输入无效。
  3. 如果用户选择重试,则重新激活单元格 A1,以便用户必须重新输入不同的值。如果用户选择取消,将单元格 A1 留空并退出该单元格。

我只寻求 VBA 解决方案,而不是 Excel 的内置数据验证功能(出于多种原因)。

谢谢大家!

试试这个作为起点。如果你插入一个 "Shape" 并将这个宏赋值给它。单击该形状可用作 运行 宏的按钮。

Sub Macro1()

Dim v1 As Variant
Dim loop1, msgbutton As Long

v1 = Cells(1, 1).Value 'read the value in cell A1

For loop1 = 1 To 100
    'compare v1 with cells range B1 to B100
    If v1 = Cells(loop1, 2).Value Then Exit For
Next loop1

'if there is a match the loop will exit before reaching 101
If loop1 > 100 Then
    'no match so make a message box
    msgbutton = MsgBox("The data is invalid.", 5, "Box Title")
    If msgbutton = 4 Then 'retry
        Cells(1, 1).Value = Empty
        Cells(1, 1).Select
    Else 'cancel
        Cells(1, 1).Value = Empty
    End If
Else 'it's a match
    Stop 'your code here
End If

End Sub