UserForm在创建新数据之前检查现有列表

时间:2018-10-12 07:01:56

标签: excel vba

我正在寻找一种仅通过UserForm控制的列表中唯一ID值的获取方法。

我有很多填满的文本框,但是在我的整个列表中,只有一个名为“ CHARGE”的框会出现。因此,在将新位置添加到我的列表之前,我需要对宏进行一些检查。

我的唯一ID是:Me.E1GCharge

我的代码:

Private Sub SaveData()
'Copy input values to sheet.
Dim lRow As Long
Dim ws As Worksheet
Set ws = sheet1
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).row
With ws

'ME.E1GCharge should exist only one time in my list. 
'If i try to make by mistake it one more time it should be not possible
    .Cells(lRow, 1).Value = Me.E1GCharge.Value
    .Cells(lRow, 3).Value = Me.E1GMatName.Value
    .Cells(lRow, 4).Value = Me.E1Gtype.Value
    .Cells(lRow, 5).Value = Me.E1GMatNumber.Value
    .Cells(lRow, 6).Value = Format(Me.E1GExpiryDate.Value, "mmm.yyyy")
    .Cells(lRow, 7).Value = Me.E1GBoxPcs.Value
    .Cells(lRow, 8).Value = Me.E1GAmmount.Value
    .Cells(lRow, 9).Value = Me.E1GUnit.Value
    .Cells(lRow, 10).Value = Me.E1Gkonz.Value

End With
'Clear input controls.
Me.E1GMatName.Value = ""
Me.E1Gtype.Value = ""
Me.E1GMatNumber.Value = ""
Me.E1GExpiryDate.Value = ""
Me.E1GBoxPcs.Value = ""
Me.E1GAmmount.Value = ""
Me.E1Gkonz.Value = ""
Me.E1GUnit.Value = ""

Call GetData

结束子

1 个答案:

答案 0 :(得分:1)

您可以遍历所有现有的vlaues并检查您要添加的费用是否已经存在:

Dim i as Integer
For i = 1 To lRow
  If ws.Cells(i, 1).Value = Me.E1GCharge.Value then
    Msgbox "This Value already exists!"
    Exit Sub
  End If
next i