2017-07-27 69 views
-1

會需要一些幫助,以兩行Excel中比較,突出差異。2行之間和比較突出的區別

我有這樣的代碼:

With ActiveSheet 

    Last_Column = .Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column 

    For lLoop = 1 To Last_Column 
     If .Cells(1, lLoop).VALUE <> .Cells(2, lLoop).VALUE Then 
      .Cells(1, lLoop).Interior.ColorIndex = 4    
     End If  
    Next 

End With 

但只比較前兩排。你能幫我行之間比較(1 & 2,3 & 4,5 & 6等),直到紙張的末端和突出的差異。

回答

1

嘗試代碼註釋中下面的代碼,解釋:

Option Explicit 

Sub CompareRows() 

Dim i As Long, Col As Long 
Dim LastRow As Long, Last_Column As Long 

With Worksheets("Sheet1") '<-- modify to your sheet's name (don't rely on ActiveSheet) 
    ' get last row 
    LastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 
    ' first add a loop of rows, step every 2 
    For i = 1 To LastRow Step 2 
     Last_Column = .Cells(i, .Columns.Count).End(xlToLeft).Column ' get last column in current row 

     ' loop through columns 
     For Col = 1 To Last_Column 
      If .Cells(i, Col).Value <> .Cells(i + 1, Col).Value Then 
       .Cells(i, Col).Interior.ColorIndex = 4 
      End If 
     Next Col    
    Next i 
End With 

End Sub 
+0

如果某些行是隱藏的,需要跳過?或者如果某些列被隱藏起來會怎樣?底線:如果沒有盡頭,我們應該堅持原來要求的OP,並且不應該試圖強加我們自己的假設分析。 – sktneer

+0

@sktneer是的,這是真的,但這種情況太明顯了,至少對我來說(至少對我來說) –

+0

工作很好。謝謝! – Sona123

0

你會只爲1和2行工作,因爲你已經很難在碼編碼他們,你也通過列循環通過行不循環的代碼。

你需要兩個循環,一個循環通過行和列通過另一循環。

試試這個...

Sub CompareRows() 
Dim LastRow As Long, LastColumn As Long 
Dim i As Long, j As Long 
LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 
LastColumn = Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column 

For i = 1 To LastRow Step 2 
    For j = 1 To LastColumn 
     If Cells(i, j) <> Cells(i + 1, j) Then Cells(i, j).Interior.ColorIndex = 4 
    Next j 
Next i 
End Sub