检查一个值是否存在于一个范围内或不与VBA

我正在检查一个值是否存在于一个范围内。 如果不存在,那么我希望它跳转到WriteProcess否则我希望它给出一个消息框,说它存在并退出子。

这是代码,

  'Write the Selected Value in the Range - Next Available row in the Column of Source For i = TableStartingRow + 1 To AddNewEntrow If Range(EntryColLett & i).Value = wb21Tool.Sheets("Home").ComboBox1.Value Then MsgBox "The data exists in the Table" GoTo StopSub Else GoTo WriteProcess End If Next WriteProcess: wbTool.Sheets("Home").Range(EntryColLett & AddNewEntrow).Value = wb21Tool.Sheets("Home").ComboBox1.Value StopSub: 'Turn on the ScreenUpdate Application.ScreenUpdating = True 

请分享你的想法。 谢谢。

如果您需要在执行“WriteProcess”之前检查每一行,可以使用其他解决scheme:

  Dim bExists As Boolean bExists = False 'Write the Selected Value in the Range - Next Available row in the Column of Source For i = TableStartingRow + 1 To AddNewEntrow If Range(EntryColLett & i).Value = wb21Tool.Sheets("Home").ComboBox1.Value Then bExists = True MsgBox "The data exists in the Table" Exit For End If Next If Not bExists Then wbTool.Sheets("Home").Range(EntryColLett & AddNewEntrow).Value = wb21Tool.Sheets("Home").ComboBox1.Value 'Turn on the ScreenUpdate Application.ScreenUpdating = True 

你的问题是,如果循环过期(耗尽所有的迭代),没有控制来防止它进入WriteProcess。

这是使用GoTo语句的一个问题。 最好把这些降到最低。 例如,虽然这并不检查每一行,只是一个例子,你可能会避免额外的GoTo

  'Write the Selected Value in the Range - Next Available row in the Column of Source For i = TableStartingRow + 1 To AddNewEntrow If Range(EntryColLett & i).Value = wb21Tool.Sheets("Home").ComboBox1.Value Then MsgBox "The data exists in the Table" GoTo StopSub Else wbTool.Sheets("Home").Range(EntryColLett & AddNewEntrow).Value = wb21Tool.Sheets("Home").ComboBox1.Value End If Next StopSub: 'Turn on the ScreenUpdate Application.ScreenUpdating = True 

然而,对表数据的暴力迭代似乎是不必要的,如果你需要检查所有的行int他表可能更好的是使用Find方法。

假设EntryColLet是表示列字母的string:

  Dim tblRange as Range Dim foundRow as Range Set tblRange = Range(EntryColLet & (TableStartingRow+1) & ":" & EntryColLet & AddNewEntRow) Set foundRow = tblRange.Find(wb21Tool.Sheets("Home").ComboBox1.Value) If foundRow Is Nothing Then 'The value doesn't exist in the table, so do something ' Else 'The value exists already MsgBox "The data exists in the Table" GoTo StopSub End If 'More code, if you have any... StopSub: Application.ScreenUpdating = True 

关于剩下的GoTo – 如果没有更多的代码在条件之后执行If foundRow Is Nothing则可以删除整个Else子句 GoTo标签:

  Dim tblRange as Range Dim foundRow as Range Set tblRange = Range(EntryColLet & (TableStartingRow+1) & ":" & EntryColLet & AddNewEntRow) Set foundRow = tblRange.Find(wb21Tool.Sheets("Home").ComboBox1.Value) If foundRow Is Nothing Then 'The value doesn't exist in the table, so do something End If Application.ScreenUpdating = True End Sub