-1

我有一个 3 张纸的 excel 工作簿。这些工作表都包含名称列表,所有列表在某些点重叠,因为它们来自不同的来源。

我试图使工作表 1 成为唯一列表,即。a 以便它只包含 sheet2 和 sheet3 中不存在的名称。

我被指出使用数据>删除重复项的方向,但这不适用于跨工作表,有没有办法使用vba宏来完成?

4

1 回答 1

2

你可以只在表格的一侧有几列用于Sheet 1表格VLOOKUP2 和 3 - 如果找到匹配项,则它应该返回 1,否则返回 0。
然后一个 excel 例程将只扫描这两列是否为 1 - 如果它找到一个然后删除该行。

这是我正在谈论的公式的示例:

在此处输入图像描述

假设column D将只是 和 的B总和C

然后宏可以在 D 列中运行,以查找任何值>0

从循环中对集合进行操作并不是真正的最佳实践,而是像下面这样循环遍历删除行的单元格:

Option Explicit

Sub deleteRows()

Dim i As Integer
i = 2
Do
    If Cells(i, 4) > 0 Then
        Cells(i, 4).EntireRow.Delete xlUp
    Else
        i = i + 1
    End If
Loop Until IsEmpty(Cells(i, 4)) = True

End Sub

sheet 2另一种方法是将所有名称sheet 3array. 然后返回sheet 1并为每个名称运行数组测试,如果它等于任何值,并且它确实删除了整个行。所以要使用数组,它会像下面这样;这假设每个列表都在column A并开始于row 2...

Sub Macro1()

    Dim names() As String
    Dim i As Integer
    i = 1

    'add names from sheet 2 into the array
    Do
        ReDim Preserve names(i)
        names(i) = ThisWorkbook.Worksheets("Sheet2").Cells(i + 1, 1)
        i = i + 1
    Loop Until IsEmpty(ThisWorkbook.Worksheets("Sheet2").Cells(i + 1, 1)) = True

    'add names from sheet 3 into the array
    Do
        ReDim Preserve names(i)
        names(i) = ThisWorkbook.Worksheets("Sheet3").Cells(i + 1, 1)
        i = i + 1
    Loop Until IsEmpty(ThisWorkbook.Worksheets("Sheet3").Cells(i + 1, 1)) = True

    'use the names array to test each row in sheet 1
    Dim j As Integer
    j = 2
    Do

        Dim deleteOccured As Boolean
        deleteOccured = False

        Dim x
        For Each x In names
            If x = Cells(j, 1) Then
                Cells(j, 1).EntireRow.Delete xlUp
                deleteOccured = True
            End If
        Next x

        If deleteOccured = False Then
            j = j + 1
        End If
        deleteOccured = False

    Loop Until IsEmpty(Cells(j, 1)) = True

End Sub

警告 我需要强调这些循环并不完美:任何编码的一般最佳实践是,在从该循环内对同一数组执行操作时,您永远不应该循环遍历数组.....我希望有人会帮助我解决这个问题。

于 2012-12-22T13:21:18.167 回答