这段代码检查userform文本框中的重复值,并强制用户填写信息。效果很好!我唯一的问题是现在我无法在不触发事件的情况下卸载用户窗体,如果我试图完全取消那么这就是问题...(我有一些要启动...)
你对如何绕过或压制这个有什么想法吗?
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
我已经尝试将事件抑制为布尔值,关闭显示警报无效...
有任何想法吗?
Daniel,使用TextBox1_Change事件会更好。当您键入时,此事件将进行检查,并且IF语句中的“Exiting Sub”也不会关闭用户窗体 - 当然,除非您想要它。您可以在TextBox的DesignBox模式下添加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