2017-02-09 63 views
0

我有一個表有行ID,我想刪除每個行ID與基於價格標準相同的行ID。如何刪除具有條件的範圍中的乘法行?

我能刪除行,但如何將我刪除,如果它是乘法

如果價格= 700,刪除行ID的3和4的整個範圍。我可以刪除具有700的行,但不知道如何刪除具有相同ID的其他行。

enter image description here

for i = 1 to 10 
    if cells(i,3).value = 700 then 
     cells(i,3).EntireRow.Delete 
     'how to delete the other row that has the same row id? 
    End if 
next i 
+2

您還需要你的循環改變向後工作,即'For I = 10 To 1 Step -1'。 – YowE3K

+0

您的實際數據集中是否有不同的跟蹤號碼,或者ColA中的所有值是否相同? –

+0

將會有不同的跟蹤號碼乘以相同的行ID 1,2,3,4,5,我想同時刪除具有700個不同跟蹤號碼的乘法行。 –

回答

1

曾在我的小測試:

Sub DeleteRows() 

    Dim rng As Range, rw As Range, k, dict, x As Long 
    Dim rngDelete As Range 

    Set dict = CreateObject("scripting.dictionary") 

    Set rng = ActiveSheet.Range("A1").CurrentRegion 

    'first pass - find all "duplicate" id's 
    For x = 2 To rng.Rows.Count 
     Set rw = rng.Rows(x) 
     k = rw.Cells(1) & "~" & rw.Cells(2) 
     If Application.CountIfs(rng.Columns(1), rw.Cells(1), _ 
           rng.Columns(3), rw.Cells(3)) > 1 Then 
      rw.Interior.Color = vbYellow '<<< for QC 
      dict.Add k, True '<<remember this combination 
     End If 
    Next x 
    'second pass - flag rows for deletion 
    For x = 2 To rng.Rows.Count 
     Set rw = rng.Rows(x) 
     k = rw.Cells(1) & "~" & rw.Cells(2) 
     If dict.exists(k) Then BuildRange rngDelete, rw 
    Next x 

    If Not rngDelete Is Nothing Then rngDelete.Delete 

End Sub 

Sub BuildRange(ByRef rngTot As Range, ByRef rngAdd As Range) 
    If Not rngTot Is Nothing Then 
     Set rngTot = Application.Union(rngTot, rngAdd) 
    Else 
     Set rngTot = rngAdd 
    End If 
End Sub 
0

希望這樣的事情能夠適應您的需求:

Sub tgr() 

    Const sIDCol As String = "B" 
    Const sPriceCol As String = "C" 

    Dim ws As Worksheet 
    Dim rCheck As Range 
    Dim rCheckCell As Range 
    Dim rDel As Range 

    Set ws = ActiveWorkbook.ActiveSheet 
    Set rCheck = ws.Range(ws.Cells(1, sPriceCol), ws.Cells(ws.Rows.Count, sPriceCol).End(xlUp)) 

    For Each rCheckCell In rCheck.Cells        'Loop through each cell in rCheck 
     If rCheckCell.Value = 700 Then        'If the cell = 700 
      Select Case ws.Cells(rCheckCell.Row, sIDCol).Value 
       Case 3, 4           'And the cell in column sIDCol in the same row = 3 or 4 
        If rDel Is Nothing Then       'then add the cell to the rDel range 
         Set rDel = rCheckCell 
        Else 
         Set rDel = Union(rDel, rCheckCell) 
        End If 

       Case Else 
        'Do nothing 

      End Select 
     End If 
    Next rCheckCell 

    If Not rDel Is Nothing Then rDel.EntireRow.Delete    'If there's anything in the rDel range, delete those rows 

End Sub 
+0

我有多次追蹤號碼,不知道這是否適用於多次追蹤號碼。 –

+0

@pokemon_Man根據您的描述和您的嘗試代碼,不會查看追蹤編號。這個提供的代碼也會忽略跟蹤號碼,它只會查看價格以檢查是否爲700,而行ID是否爲3或4.所有符合該條件的行都將被刪除,而不管跟蹤號碼如何。你的要求有所不同嗎? – tigeravatar

+0

是的,我的圖片只顯示1組跟蹤號碼,但有多個,我需要刪除,讓每個跟蹤號碼中的每個不同的ID號碼說700。 –