使用VBA检查某个范围内是否存在值

时间:2017-05-09 14:54:16

标签: excel vba excel-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

请分享您的想法。感谢。

2 个答案:

答案 0 :(得分:4)

你的问题是,如果循环到期(耗尽所有迭代),则无法控制它进入WriteProcess。

这是使用{-# LANGUAGE RankNTypes #-} sum' :: Num b => (forall a. [a] -> b) -> [c] -> [d] -> b sum' f l1 l2 = f l1 + f l2 main = print $ sum' length [1,2] ['a','b'] 语句的一个问题。最好将这些保持在最低限度。例如,虽然这不会检查每个行,但只是一个例子,说明如何避免额外的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 方法。

假设Find是表示列字母的字符串:

EntryColLet

关于剩余的 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

答案 1 :(得分:3)

备用解决方案,如果您需要在执行“WriteProcess”之前检查每一行:

    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