【问题标题】:running an excel macro that compares selected cells运行比较选定单元格的 excel 宏
【发布时间】:2013-10-14 18:25:48
【问题描述】:

我想在选定的单元格上运行一个宏 - 宏将一个单元格与它下面的相邻单元格进行比较 - 改变它们的颜色并移动到下一对单元格。

这是一个一维数组,我想比较每对单元格(第一个与第二个,第三个与第四个等)

我尝试过使用

For Each cell In Selection

但是我不知道如何将给定的单元格与它下面的单元格进行比较。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    以下是示例代码。

    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
    

    【讨论】:

    • 谢谢,但这会将每个单元格与其下方的单元格进行比较。我想一次检查 2 对,然后转到下一对。我添加了一个条件以满足我的需要,但如果你能解释如何做到这一点,它可能会帮助其他人。
    • 我的代码是成对比较。你可能想看看
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      相关资源
      最近更新 更多