Excel vba를 사용하여 특정 기준을 충족하는 섹션의 한 항목을 기반으로 데이터 섹션 삭제

스티븐

데이터가있는 엑셀 시트 (시트 A라고하자)가 하나 있고 빈 행으로 구분되고 N 열의 공통 항목으로 그룹화되어 그룹화됩니다. 각 그룹 내에서 다른 엑셀 시트 (시트라고 말할 수 있음)를 확인해야합니다. B) 다른 통합 문서에서 시트 A의 A 열에있는 항목이 시트 B의 C 열에있는 항목과 일치하는지 확인합니다. C 열 항목 중 하나가 첫 번째 시트의 단일 그룹에서 A 열 항목의 항목과 일치하는 경우 , 나는 그 그룹에 대해 아무것도하지 않습니다. 일치하는 항목이 없으면 전체 그룹을 삭제해야합니다. 아래는 내 시도이지만 주로 1. 그룹화를 삭제하는 방법과 2. 각 시트 / 열을 올바르게 호출하는 방법과 혼동됩니다.

Sub DeleteAdjacent()
    Dim wb1 As Workbook, Dim wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet
    Dim lastrow1 As Long, Dim lastrow2 As Long, Dim i As Long, Dim j As Long
    Set wb1 = Workbooks("Workbook1.xlsx")
    Set wb2 = Workbooks("Workbook2.xlsx")
    Set sh2 = wb2.Sheets(“Sheet B”)
    Set sh1 = wb1.Sheets("Sheet A")
    lastrow1 = sh1.Cells(Rows.Count, 1).End(xlUp).Row
    lastrow2 = sh2.Cells(Rows.Count, 1).End(xlUp).Row
    For j = lastrow1 To 1 Step -1
        cell = "N" & j
        cell1 = "N" & (j - 1)
        Do While sh1.Cells(j, cell).Value = sh1.Cells(j, cell1).Value
            For i = lastrow2 To 1 Step -1
                cell2 = "C" & i
                cell3 = "A" & j
                If sh1.Cells(j, cell3).Value = sh2.Cells(i, cell2).Value Then
                    Do While sh1.Cells(j, cell).Value = sh1.Cells(j, cell1).Value
                        sh1.Range(j, cell).EntireRow.Delete
                    Loop
                End If
            Next i
        Loop
    Next j
End Sub

편집 : 내 시도를 더 자세히 살펴보면 실제로 내가하고 싶은 것과 반대되는 작업을 수행 할 것입니다. 실제로 정반대를 원할 때 일치가있을 때 전체 그룹을 삭제하려고했습니다. 그러면 아래 부분이 변경되어야한다고 생각합니다.

If sh1.Cells(j, cell3).Value = sh2.Cells(i, cell2).Value Then
    Do While sh1.Cells(j, cell).Value = sh1.Cells(j, cell1).Value
        sh1.Range.Cells(j, cell).EntireRow.Delete
    Loop
End If

이 문제를 해결하려는 시도가 너무 간단할까요?

If sh1.Cells(j, cell3).Value <> sh2.Cells(i, cell2).Value Then
    Do While sh1.Cells(j, cell).Value = sh1.Cells(j, cell1).Value
        sh1.Range.Cells(j, cell).EntireRow.Delete
    Loop
End If
Ambie

이 문제를 공격한다면 A와 C를 비교하지 않고 동일한 프로세스에서 그룹 루핑 검사를 수행하지 않을 것이라고 생각합니다. 먼저 그룹에 대한 값 맵을 만드는 경우 문제를 해결하는 것이 더 쉬울 수 있습니다. 그룹 1, 3 및 5에 10의 값이 있다고 가정하면 10을 확인하고 향후 확인에서 즉시 3 개의 그룹을 제거 할 수 있습니다. 의 A CollectionCollections조회 key가 매우 빠르며 저장되는 항목 수에 대해 걱정할 필요가 없으므로 이것에 대해 잘 도움이 될 것 입니다.

또한 Ranges각 그룹 대한 컬렉션이있는 경우 일치하는 그룹을 제거한 다음 한 번에 나머지를 모두 삭제하는 간단한 프로세스가 Ranges됩니다.

아래 코드는이를 수행해야합니다 (하지만 행 삭제 코드와 마찬가지로 먼저 원시 데이터를 백업하는 것이 좋습니다!).

Public Sub DeleteAdjacent()
    Dim ws As Worksheet
    Dim valueGroupMap As Collection
    Dim groupRanges As Collection
    Dim values As Collection
    Dim lastRow As Long
    Dim groupRng As Range
    Dim valueCell As Range
    Dim groupCell As Range
    Dim rng As Range
    Dim v As Variant
    Dim r As Long

    'Read the Column A worksheet
    Set ws = Workbooks("Workbook1.xlsx").Worksheets("Sheet A")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1 '+1 to get a blank row at end

    'Define the value map group ranges
    Set valueGroupMap = New Collection
    Set groupRanges = New Collection
    Set groupRng = ws.Cells(1, "N")

    For r = 1 To lastRow

        Set valueCell = ws.Cells(r, "A")
        Set groupCell = ws.Cells(r, "N")

        If Len(CStr(groupCell.Value2)) = 0 Then
            'We've reached the end of a group
            Set rng = ws.Range(groupRng, groupCell.Offset(-1))
            groupRanges.Add rng, CStr(groupRng.Value2)
            Set groupRng = Nothing
        Else
            'We're working within a group
            If groupRng Is Nothing Then
                Set groupRng = groupCell
            End If
            'Create the value to group map
            Set values = Nothing
            On Error Resume Next
            Set values = valueGroupMap(CStr(valueCell.Value2))
            On Error GoTo 0
            If values Is Nothing Then
                Set values = New Collection
                valueGroupMap.Add values, CStr(valueCell.Value2)
            End If
            values.Add CStr(groupRng.Value2)

        End If

    Next


    'Read the Column C worksheet
    Set ws = Workbooks("Workbook2.xlsx").Worksheets("Sheet B")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    On Error Resume Next
    For r = 1 To lastRow
        'Check if we have the value
        Set values = Nothing
        Set values = valueGroupMap(CStr(ws.Cells(r, "C").Value2))
        If Not values Is Nothing Then
            'We do, so remove the group ranges from our list
            For Each v In values
                groupRanges.Remove CStr(v)
            Next
        End If
    Next
    On Error GoTo 0

    'Create a range of the groups still remaining in the list
    Set rng = Nothing
    For Each groupRng In groupRanges
        If rng Is Nothing Then
            Set rng = groupRng
        Else
            Set rng = Union(rng, groupRng)
        End If
    Next

    'Delete that range
    rng.EntireRow.Delete

End Sub

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관