簡體   English   中英

運行比較選定單元格的Excel宏

[英]running an excel macro that compares selected cells

我想在選定的單元格上運行宏-該宏將一個單元格與其下方的鄰居進行比較-更改其顏色,然后移至下一對單元格。

這是一個1維數組,我要在其中比較每對單元格(第1個與第2個單元格,第3個與第4個單元格等)。

我嘗試與

For Each cell In Selection

但是我不知道如何將給定的單元格與下面的單元格進行比較。

下面是示例代碼。

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
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM