检查当前工作表中是否已经存在一组数据

时间:2019-02-12 09:25:43

标签: excel vba

this is how the table where I have to search for the data would look like but filled with lots of data That's the table items I am searching for. I'm looking for the data in this exact order so the whole block of data我有一张装满数据的大桌子。我想做的是检查此表中是否已经存在一组数据。我已将要查找的数据插入单独的工作表中。带有我要查找的表项的范围称为“ SearchedData”,而我正在检查是否包含我要查找的数据的区域称为“ SearchArea”。

我的代码仅向我显示数据将存在,但在我正在处理的工作表中不存在,因此我的代码一定存在问题。在这方面的任何帮助将不胜感激!

Sub CheckWetherDataExists()

    Dim SearchedData As Variant
    Dim SearchArea As Variant

    SearchedData = ThisWorkbook.Worksheets("Tabelle2").Range("C5:G8").Value
    SearchArea = ThisWorkbook.Worksheets("Tabelle1").Range("A:E").Value

    If SearchArea = SearchedData Then
    MsgBox ("Searched Data already exists")

    Else: MsgBox ("Searched Data is missing")
    End If


End Sub

2 个答案:

答案 0 :(得分:1)

这是一种更复杂的解决方法。

想象thisIs.parent().next().next().find(ELEM).val(result.fields.quantity);如下:

enter image description here

Tabelle2如下:

enter image description here

我建议使用Range.Find method查找第一个单元格数据的第一个出现位置,此处用Tabelle1表示。然后检查其余数据是否也正确/正确。循环执行此操作,直到检查所有情况。

因此,在11中,黄色区域将被塞住,但唯一的完全匹配项是在Tabelle1,它将被视为重复项。

A14:E17

答案 1 :(得分:1)

我相信这段代码会相当快地完成您想要的事情。

Sub CheckWetherDataExists()

    Dim SearchedData As Variant
    Dim SearchArea As Variant
    Dim LookFor() As String
    Dim LookIn() As String
    Dim R As Long, C As Long

    SearchedData = ThisWorkbook.Worksheets("Tabelle2").Range("C5:G8").Value
    LookFor = MergedRows(SearchedData)

    With ThisWorkbook.Worksheets("Tabelle1")
        SearchArea = .Range(.Cells(2, 1), .Cells(.Rows.Count, 5).End(xlUp)).Value
    End With
    LookIn = MergedRows(SearchArea)

    For R = 1 To UBound(LookIn)
        If LookIn(R) = LookFor(1) Then
            If R < UBound(LookIn) - 2 Then
                For C = 2 To UBound(LookFor)
                    If LookIn(R + C - 1) <> LookFor(C) Then Exit For
                Next C
                If C > UBound(LookFor) Then
                    MsgBox "Match found in Row " & R
                    Exit For
                End If
            End If
        End If
    Next R
End Sub

Private Function MergedRows(RngVal As Variant) As String()

    Dim Fun() As String
    Dim R As Long, C As Long

    ReDim Fun(1 To UBound(RngVal))

    For R = 1 To UBound(RngVal)
        For C = 1 To UBound(RngVal, 2)
            Fun(R) = Fun(R) & "," & RngVal(R, C)
        Next C
    Next R
    MergedRows = Fun
End Function

代码创建了SearchedData和SearchArea数据的5个单元格的合并字符串。这项工作由功能 MergedRows 完成。在此过程中,SearchedData变成数组LookFor(1到3)和LookIn(1到LastRow)。接下来,将LookFor的第一个元素(代表一行)与LookIn的每个元素(代表一行)进行比较。如果找到匹配项,则还将比较其他两行。当所有三个元素(行)都匹配时,将发出一条消息,并终止搜索。