【问题标题】:Deleting Duplicates while ignoring blank cells in VBA删除重复项同时忽略 VBA 中的空白单元格
【发布时间】:2019-07-30 22:10:57
【问题描述】:

我在 VBA 中有一些代码试图删除重复的事务 ID。但是,我想修改代码以仅删除具有事务 ID 的重复项 - 因此,如果没有事务 ID,我希望该行不受影响。下面是我的代码:

With MySheet
    newLastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    newLastCol = .Cells(5 & .Columns.Count).End(xlToLeft).Column
    Set Newrange = .Range(.Cells(5, 1), .Cells(newLastRow, newLastCol))
    Newrange.RemoveDuplicates Columns:=32, Header:= _
        xlYes
End With

我还想知道 - 在 remove.duplicates 命令中 - 有没有一种方法可以让我想要查看的列被命名而不是 32,以防我在以后添加或删除列? 这是数据的图像:我希望保留这 3 个空格的 ExchTransID 列。

【问题讨论】:

  • 听起来你需要做一个循环来评估符合哪些标准...... If len(cells(i,11).value) > 0 Then 可能是给你一个好的开始。
  • 你能把这个表格变成官方的Excel“表格”吗?插入-> 表格。如果可以,那么您已经将表格转换为 Excel 在 VBA 中所称的 ListObject。 ListObjects 的优点之一是您可以在 VBA 代码中通过列名来引用列。
  • 不,我真的不能作为一个表格 - 我想列问题不是最紧迫的
  • 啊,太糟糕了。它们简化了这些类型的任务。祝你好运!

标签: excel vba duplicates


【解决方案1】:

修改并尝试以下:

Option Explicit

Sub test()

    Dim Lastrow As Long, Times As Long, i As Long
    Dim rng As Range
    Dim str As String

    'Indicate the sheet your want to work with
    With ThisWorkbook.Worksheets("Sheet1")
        'Find the last row with IDs
        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        'Set the range with all IDS
        Set rng = .Range("A1:A" & Lastrow)
        'Loop column from buttom to top
        For i = Lastrow To 1 Step -1
            str = .Range("A" & i).Value
            If str <> "" Then
                Times = Application.WorksheetFunction.CountIf(rng, str)
                If Times > 1 Then
                    .Rows(i).EntireRow.Delete
                End If
            End If
        Next i
    End With
End Sub

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多