【发布时间】:2017-01-18 21:03:37
【问题描述】:
您好,我收到了此代码,并且有一个功能可以检查用户是否要输入已经存在的发票编号。实际上,此功能仅在整个表单已填写并即将存储在表格中时才会发生,但我希望在用户输入数据后立即进行验证。
这是我的实际代码:
Private Sub CommandButton1_Click()
Dim L As Long
Dim factureWs As Worksheet
Dim rng As Range
Dim thColor As XlThemeColor
If MsgBox("Confirm?", vbYesNo, "Confirming new invoice") = vbNo Then Exit Sub
Set factureWs = Worksheets("FACTURE") '<--| set the worksheet you want to work with
L = GetLastNonEmptyRow(factureWs, "D", 12) + 1 '<--| get passed worksheet first empty row after last non empty one in column "D" from row 12 (included)
If L > 0 Then If Not CheckDuplicate(Me.TextBox2, factureWs.Range("D12:D" & L - 1)) Then Exit Sub '<--| exit if duplicated non accepted by the user
FillRanges factureWs, L '<--| fill worksheet ranges with userfom controls values
With Me
If .OptionButton1 Then
FormatCell Range("B" & L), xlThemeColorAccent3
ElseIf .OptionButton2 Then
FormatCell Range("B" & L), xlThemeColorAccent1
ElseIf .OptionButton3 Then
FormatCell Range("B" & L), xlThemeColorAccent4
Else
FormatCell Range("B" & L), xlThemeColorAccent2
End If
End With
End Sub
这里是函数
Function CheckDuplicate(factureNo As String, rng As Range) As Boolean
Dim f As Range
Set f = rng.Find(what:=factureNo, LookIn:=xlValues, lookat:=xlWhole)
If Not f Is Nothing Then
CheckDuplicate = MsgBox("This invoice number already exist!" & vbCrLf & vbCrLf & "Continue?", vbExclamation + vbYesNo, "Duplicate alert") = vbYes
Else
CheckDuplicate = True
End If
End Function
感谢您的帮助!
【问题讨论】:
-
当用户在
factureWs.Range("D12:D" & L - 1))中输入数据时是否要查找重复项?在这种情况下,如果您的“FACTURE”表出现Worksheet_SelectionChange(ByVal Target As Range),您需要致电Function CheckDuplicate。
标签: forms vba validation duplicates