要在添加数据之前先判断文本框 'TextBoxCustom' 的数据在工作表 '客户总表' 中是否已经存在,可以使用 Application.Match 函数来查找匹配项。

以下是修改后的代码:

Private Sub 添加_Click()
    Dim ws As Worksheet
    Dim lRow As Long
    
    Set ws = Worksheets("客户总表")
    
    ' 判断文本框 'TextBoxCustom' 的数据是否已经存在
    Dim matchValue As Variant
    matchValue = Application.Match(Me.TextBoxCustom.Value, ws.Range("B:B"), 0)
    
    If Not IsError(matchValue) Then ' 数据已存在
        MsgBox "该客户已经存在无需重复创建!", vbInformation, "系统提示"
        Exit Sub
    End If
    
    lRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row + 1
    
    ws.Cells(lRow, 2).Value = Me.TextBoxCustom.Value
    ws.Cells(lRow, 3).Value = Me.TextBoxLocation.Value
    ws.Cells(lRow, 4).Value = Me.TextBoxContact.Value
    ws.Cells(lRow, 5).Value = Me.TextBoxPosition.Value
    ws.Cells(lRow, 6).Value = Me.TextBoxTel.Value
    ws.Cells(lRow, 7).Value = Me.TextBoxMailing.Value
    ws.Cells(lRow, 8).Value = Me.TextBoxEmail.Value
    ws.Cells(lRow, 9).Value = Me.TextBoxComment.Value
    
    ' Determine the last row of data
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
    
    ' Sort the data from the first row of data to the last row of data
    ws.Range("B9:I" & lastRow).Sort Key1:=ws.Range("B9"), Order1:=xlDescending, Header:=xlGuess, _
        OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
    
    Me.Hide
End Sub

在修改后的代码中,我使用 Application.Match 函数来查找文本框 'TextBoxCustom' 的值是否在工作表 '客户总表' 的 B 列中已存在。如果存在,函数返回匹配的行号,否则返回错误值。通过检查 IsError(matchValue) 来判断是否存在匹配项。如果存在匹配项,则显示提示对话框并退出子程序。

如果不存在匹配项,则继续执行添加数据的操作。

Excel VBA: 添加数据前判断客户是否已存在

原文地址: https://www.cveoy.top/t/topic/ciAr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录