excel - UserForm 在创建新数据 VBA 之前检查现有列表
问题描述
我想创建一个带有输入的用户表单:姓名(TextBox1),姓氏(TextBox2),出生日期(TextBox3)和1个输出,基本上是他们的ID(从1到inf)。困扰我的是,我想编写代码,如果让我们说名称和姓氏已经存在于数据库中,则会弹出 msg 并且表单将重置,否则所有内容都将被放入表中。我设法做到了。现在的问题是,如果我确实输入了已经存在的姓名和姓氏,它不会将其输入到表格中并会显示消息,但即使它不存在,消息仍会弹出但它会将其输入到表格中。这是代码:
Private Sub CommandButton1_Click()
Dim iRow As Long
Dim ws As Worksheet
Set ws = Sheet2
Dim a As Integer
Application.ScreenUpdating = False
iRow = ws.Range("A1048576").End(xlUp).Row + 1
If Not (TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "") Then
With ws
Label1.Caption = iRow - 1
For a = 1 To iRow
If (ws.Cells(a, 2).Value = TextBox1.Value And ws.Cells(a, 3).Value = TextBox2.Value) Then
MsgBox "Values you entered already exists!"
Call Reset
Exit Sub
Else
.Range("A" & iRow).Value = Label1.Caption
.Range("B" & iRow).Value = TextBox1.Value
.Range("C" & iRow).Value = TextBox2.Value
.Range("D" & iRow).Value = TextBox3.Value
End If
Next a
End With
End If
Application.ScreenUpdating = True
End Sub
解决方案
问题是您正在检查插入新记录的行。因此,对于与新记录不匹配的每一行,都会在 iRow 中插入。当循环结束时,它会检查 iRow,匹配并显示消息。将代码分为 2 个步骤,首先检查然后更新或重置。
Private Sub CommandButton1_Click()
If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Then
Exit Sub
End If
Dim ws As Worksheet
Dim iRow As Long, r As Long, bExists As Boolean
Set ws = Sheet2
iRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
' check exists
For r = 1 To iRow
If (ws.Cells(r, 2).Value = TextBox1.Value) _
And (ws.Cells(r, 3).Value = TextBox2.Value) Then
bExists = True
Exit For
End If
Next
' update sheet
If bExists Then
MsgBox "Values you entered already exists!"
Call Reset
Exit Sub
Else
Label1.Caption = iRow
iRow = iRow + 1
With ws
.Range("A" & iRow).Value = Label1.Caption
.Range("B" & iRow).Value = TextBox1.Value
.Range("C" & iRow).Value = TextBox2.Value
.Range("D" & iRow).Value = TextBox3.Value
End With
End If
End Sub
推荐阅读
- java - 如何将数学符号(例如 R^n)放入 Java 字符串?
- r - 如何在ggplot的散点图中根据因子列最好地绘制值列的两个子集?
- javascript - 将所选内容以 PDF 格式保存到 Google 表格电子表格
- php - 如何从 php 中的选择/选项中获取多个数据到一个变量中?
- python - 从 python 下载 xls 导致格式损坏与手动下载
- python - 当我尝试创建虚拟环境时返回非零退出状态 101 给出错误
- karate - 我如何在空手道 UI 自动化中拦截 API 调用
- python - 在线程内使用 Popen 的奇怪行为
- r - 在数据帧上应用函数,包括 rbind 语句
- excel - 如何在数据透视表中找到最后一行?