我有一个UserForm,可以将新商品添加到我的库存表。
如果我能将产品变成主键,我想寻求帮助。这样“产品密钥”就无法复制。任何帮助都将深表感谢。
我的代码如下链接(似乎无法将我的代码粘贴到此框中,因为我一直收到错误,说我的代码格式不正确)抱歉给您带来不便: http://imgur.com/7xFDawO
Option Explicit
Private Sub cmdAdd_Click()
Dim row As Long
Do
row = row + 1
Loop Until (Sheets("Inventory").Cells(row, 1) = "")
Sheets("Inventory").Select
Sheets("Inventory").Cells(row, 1) = txtProdCodeAI.Value
Sheets("Inventory").Cells(row, 2) = txtProdNameAI.Value
Sheets("Inventory").Cells(row, 3) = txtQuantityAI.Value
Sheets("Inventory").Cells(row, 4) = txtSupplierAI.Value
Sheets("Inventory").Cells(row, 5) = txtSupplierNumberAI.Value
End Sub
Private Sub cmdCancel_Click()
Unload AddInventory
End Sub
P.S代码已添加到链接中的图片描述但未正确格式化
**
**
用户通过文本框输入产品代码,产品名称,数量,供应商(名称)和供应商联系电话。
主键位于A列,从第2行开始,因为有一个标题。
工作表名称称为“库存”。
如果输入相同的主键,则会弹出错误“vbokonly - 错误!产品代码已存在。请使用更新功能。”
答案 0 :(得分:3)
只需检查A列中的值:
txtProdCodeAI.Value
像这样:
Dim keyExists as Boolean
keyExists = Not Range("A1:A" & row).Find(txtProdCodeAI.Value) Is Nothing
If keyExists Then
MsgBox txtProdCodeAI.Value & " already exists!", vbCritical
Exit Sub
End If
将它放在您的代码中,如下所示:
Private Sub cmdAdd_Click()
Dim row As Long
Dim keyExists as Boolean
Do
row = row + 1
Loop Until (Sheets("Inventory").Cells(row, 1) = "")
keyExists = Not Sheets("Inventory").Range("A1:A" & row).Find(txtProdCodeAI.Value) Is Nothing
If keyExists Then
MsgBox txtProdCodeAI.Value & " already exists!", vbCritical
Exit Sub
End If
Sheets("Inventory").Select
Sheets("Inventory").Cells(row, 1) = txtProdCodeAI.Value
Sheets("Inventory").Cells(row, 2) = txtProdNameAI.Value
Sheets("Inventory").Cells(row, 3) = txtQuantityAI.Value
Sheets("Inventory").Cells(row, 4) = txtSupplierAI.Value
Sheets("Inventory").Cells(row, 5) = txtSupplierNumberAI.Value
End Sub
答案 1 :(得分:0)
在Excel中的其他解决方案,您可以在整个列中使用验证格式,在空列中,选择整个列并转到数据选项卡> 数据验证>那里:
这将限制您输入的所有值(类似主键的方案,没有欺骗),但是这样会提示错误(因为您无法输入重复值),因此在您的周期中您需要添加像这样的错误处理程序(未经测试的)
On Error GoTo ErrorHandler
Sheets("Inventory").Select
Sheets("Inventory").Cells(row, 1) = txtProdCodeAI.Value
Sheets("Inventory").Cells(row, 2) = txtProdNameAI.Value
Sheets("Inventory").Cells(row, 3) = txtQuantityAI.Value
Sheets("Inventory").Cells(row, 4) = txtSupplierAI.Value
Sheets("Inventory").Cells(row, 5) = txtSupplierNumberAI.Value
Exit Sub
ErrorHandler:
MsgBox "This Product Code" & txtProdCodeAI.Value & "is a duplicate"
Resume Next