2017-09-22 230 views
3

我是新來的excel VBA,我有一個任務需要使用VBA來完成。我正在尋找比較同一列中的值。我想開始與最後一行的比較並向上移動。篩選標準是,如果當前和最後一個數字之間的差異百分比大於3%,則將該值複製並粘貼到另一行。一旦複製並粘貼一個值,當檢查3%的差異時,應該將數據中的值與先前的複製和粘貼值進行比較。下面的例子。提前致謝。Excel VBA - 比較同一列中的行

例如,如果我的數據範圍如下所示

1100 
1285 
1290 
3005 
1500 
2020 
2030 
2040 
2050 
2060 
2070 
2080 
2100 
2500 
3000 

這應該是我的結果:

1100 
1290 
1500 
2030 
2100 
2500 
3000 

結果我已現在在那裏(3000和3005之間的差具有3005小於3%(3005/3000),因此3005不應在列表中),當它不應該在列表中。

1100 
1290 
3005 
1500 
2030 
2100 
2500 
3000 

這是我現在的代碼。提前致謝。

Sub main2() 

Dim row_a As Long 
Dim row_b As Long 
Dim l_2 

row_b = Range("D5000").End(xlUp).Row 
Cells(row_b, "d").Copy Cells(row_b, "P") 

l_2 = row_b - 1 

For i = row_b To 3 Step -1 
    a = Cells(row_b, "d").Value 
    For j = l_2 To 3 Step -1 
     If a/Cells(j, "d") <= 0.97 Or a/Cells(j, "d") >= 1.03 Then 
      Cells(j, "d").Copy Cells(j, "p") 
      a = Cells(j, "d").Value 
     End If 
    Next j 
Next i 

End Sub 
+2

按您自己的規範,3005應該是在名單上,因爲3005和1290和3005和1500之間的差異之間的差異都較大比3%...請重新審視您的規定 – jsotola

+0

@ Jonathon-Sidwell,它wou ld對這篇文章的任何讀者都有幫助,如果你至少可以描述你使用你的查詢的內容。因爲指定通緝方法似乎有些困難。 –

回答

1

@Jonathon當我通過你的代碼,發現您需要選擇列「d」值像,

如果選擇值,則沒有任何價值的任何3%附近的選擇選定的值

和選擇標準從去底部向上落入第一把它作爲你在建議(3000 3005問題)

並粘貼在列「P」

所有選定值

如果正確,那麼經過下面的代碼它滿足您的特定條件爲每個問題

「」「」「」「」「」「」「」「」「」「」「」「」「」「」 ''''''''''''''''''''''''''''''''''''' '代碼開始這裏

Sub Filter3Per() 

Dim LastRow As Integer 
Dim ComVal As String 


'''''''''Apply filter on columun with loop as per criteria 
'Read last Row from D column 
LastRow = Cells(Rows.Count, "D").End(xlUp).Row 

'Clear format color of column D 
Range("D:D").Interior.ColorIndex = -4142 

'''Clear P column 
Range("P:P").ClearContents 
'Loop Goes from botttom to top 3 row 
For i = LastRow - 1 To 1 Step -1 
    'Read compvalue 
    ComVal = Cells(i + 1, "D").Value 

    'Check for color 
    If Cells(i + 1, "D").Interior.ColorIndex <> 3 Then 

     'Loop to Check as Criteria 
     For j = i To 1 Step -1 

     'Critera 
     If ComVal/Cells(j, "D") <= 0.97 Or ComVal/Cells(j, "D") >= 1.03 Then 

     Else 
     Cells(j, "D").Interior.ColorIndex = 3 

     End If 
     Next 

    End If 

Next 

''''''''Apply filter on columun with loop as per criteria End here 
'''''''''''''''Collect value'''''''''''''''''''' 
'''Clear P column 

Range("P:P").ClearContents 
For i = 1 To LastRow 

    If Cells(i, "D").Interior.ColorIndex <> 3 Then 

    Cells(i, "P").Value = Cells(i, "D") 'add value in p Column 

    End If 
Next 
'''''''''''Collect value end here 
End Sub 

「子到此結束 ‘’」「」

+1

始終使用完全合格的範圍參考,例如'Dim ws As WorkSheet'後面跟着'Set ws = ThisWorkBook.WorkSheets(「MySheetName」)'。然後,您可以精確地參考'ws.Cells(i + 1,「D」)',而不是'Cells'。 –

+0

通過內部顏色索引而不是使用額外列來標記排除值是個不錯的主意。 –

+0

您的ComVal聲明爲字符串將導致類型錯誤。 –