2013-10-08 101 views
1

我想在選定的單元格上運行一個宏 - 在這裏宏將一個單元格與它下面的鄰居進行比較 - 改變顏色並移動到下一對單元格中。運行一個比較選定單元格的excel宏

它是A 1名維陣列,其中我想比較每一對電池(第一與第二,第三與第四等)

我試圖與

For Each cell In Selection 

工作,但然後我不不知道如何比較給定的細胞和它下面的細胞。

回答

0

下面是示例代碼。

Sub compare() 

    Dim rng As Range, cell As Range 
    Set rng = Selection ' 

    For Each cell In rng 
     'makes comparison 
     'offset(1,0) is used to find one cell below active cell 
     If cell.Value = cell.Offset(1, 0) Then 
      cell.Offset(1, 0).Interior.Color = vbRed 
     End If 
    Next 
End Sub 

更新答案

Sub compare() 

    Dim rows As Long 
    rows = Selection.rows.Count - 1 

    Dim selCol As Long 
    selCol = ActiveCell.Column 

    Dim selRow As Long 
    selRow = ActiveCell.Row 

    For i = selRow To (selRow + rows) 
     If Cells(i, selCol) = Cells(i, selCol + 1) Then 
      Range(Cells(i, selCol), Cells(i, selCol + 1)).Interior.Color = vbYellow 
     End If 
    Next 


End Sub 
+0

謝謝你,但是這每一個細胞進行比較與它下面的一個。我想一次檢查2對,然後移動到下一對。 我添加了一個條件來滿足我的需要,但是如果你能解釋如何去做,它可能會幫助其他人。 –

+0

我的代碼是兩兩比較的。你可能想看看 – sam092

0
Sub compareCells() 
    Dim i As Integer 
    'Check dimension 
    If Selection.Columns.Count <> 1 Then 
     MsgBox "not 1d array" 
     Exit Sub 
    End If 
    'Check size 
    If Selection.Rows.Count Mod 2 <> 0 Then 
     MsgBox "size not even" 
     Exit Sub 
    End If 
    For i = 1 To Selection.Count/2 
     With Selection 
     If .Cells(2 * i - 1) = .Cells(2 * i) Then 
      'what you want to do here, for e.g. , change color 
      .Cells(2 * i).Interior.Color = vbYellow 
     Else 
      'what you want to do here 
      'MsgBox "neq" 
     End If 
     End With 
    Next i 
End Sub 
相關問題