根据列中单元格的值删除重复行

时间:2014-11-03 21:11:35

标签: excel

我有以下脚本在google docs中运行良好 - >床单。对于很多行,它不能很好地工作。我猜是因为数组不断变大以跟踪值。

我需要一个可以在MS EXCEL中运行的脚本,它将删除列中具有重复值的行。 (除非该列是“”)

适用于小文件的Google文档脚本:

function removeDuplicates()
{
  var s = SpreadsheetApp.getActiveSheet();
  var c = Browser.inputBox("Please", "Type in the column name (e.g.: A, B, etc.)", Browser.Buttons.OK_CANCEL);
  var r, v;
  var aValues = [];
  try
  {
    if(c != "cancel")
    {
      r = 2; // first row is row two
      while (r <= s.getLastRow())
      {
        v = s.getRange(c + r).getValue();
        if(v != "")
        {
          if(aValues.indexOf(v) == -1)
          {
            aValues.push(v);
          }
          else
          {
            s.deleteRow(r);
            continue;
          }
        }
        r++;
      }
      Browser.msgBox("Duplicates removed!");
    }
  } catch (e) {Browser.msgBox("Error Alert:", e.message, Browser.Buttons.OK);}
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

这似乎适合这项法案。

Sub dedupe_ignore_blanks()
    Dim r As Long, v As Long, vVALs As Variant, sCOL As String
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    With ActiveSheet.Cells(1, 1).CurrentRegion
        sCOL = "B"
        sCOL = Application.InputBox("Type in the column name (e.g.: A, B, etc.)", _
            "Please", sCOL, 250, 75, "", , 2)
        If CBool(Len(sCOL)) And sCOL <> "False" Then
            For r = .Rows.Count To 2 Step -1
                If Application.CountIf(.Columns(sCOL), .Cells(r, sCOL).Value) > 1 Then _
                    .Rows(r).EntireRow.Delete
            Next r
        End If
    End With
FallThrough:
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

我从您的代码段中收集到您在数据行1中有标题行。Application.CountIF不计算空白单元格。