这段代码检查用户表单文本框中的重复值,并强制用户填写信息。很棒!我唯一的问题是,现在我无法在不触发事件的情况下卸载用户窗体,如果我要完全取消,那是个问题...(我有一些要启动...)
您对如何绕过或阻止此操作有任何想法吗?
Duplicate check code
Private Sub ItemName_exit(ByVal Cancel As MSForms.ReturnBoolean) 'checks for duplicate
If Application.WorksheetFunction.CountIf(Worksheets(2).Range("B6:B505"), ItemName.Text) > 0 Then
MsgBox ("Duplicate value, please change the name."), vbOKOnly, Title:="Duplicate"
Cancel = True
Exit Sub: End If
End Sub
我尝试将事件抑制为布尔值,关闭显示警报无效...
有什么想法吗?
答案 0 :(得分:1)
Daniel,使用TextBox1_Change事件会更好。此事件在您键入时进行检查,并且IF语句中的“退出子”也不会关闭用户窗体-当然,除非您愿意。您可以在设计模式下为TextBox添加ControlTipText,然后确保将ShowModal属性更改为False。下面的示例与您拥有的示例不同,但是可以实现目标。
代码示例:
Option Explicit
Private Sub TextBox1_Change()
Dim ws As Worksheet
Dim rng As Range
Dim intDupes As Integer
'set variables
Set ws = ThisWorkbook.Worksheets("sheetname")
Set rng = ws.Range("B6:B505")
intDupes = Application.WorksheetFunction.CountIf(rng, TextBox1.Value)
'changes color of textbox
'also, you can add a ControlTipText text to the textbox
'that informs the user what your message box did
If intDupes > 0 Then
TextBox1.BackColor = vbRed
ElseIf intDupes = 0 Then
TextBox1.BackColor = vbWhite
End If
'clean up
Set cell = Nothing: Set ws = Nothing
End Sub