使用vba比较excel中的2个单元格

时间:2015-01-21 15:55:18

标签: excel vba excel-vba

我想比较2个单元格的值,看看它们是否匹配。 我知道如何在excel上做,但我不知道如何把它放到vba代码。

输入&输出:

  1. 单元格A1的值已经在excel中。
  2. 在Cell B1中手动输入值。
  3. 单击button_click sub以查看2个单元格上的值是否相同。
  4. 在单元格C1上显示“是”或“否”
  5. Excel公式:

    =IF(A1=B1,"yes","no")
    

5 个答案:

答案 0 :(得分:4)

尝试一下:

Sub CompareCells()
    If [a1] = [b1] Then
        [c1] = "yes"
    Else
        [c1] = "no"
    End If
End Sub

将此代码分配给按钮。

答案 1 :(得分:2)

If (Range("A1").Value = Range("B1").Value) Then
    Range("C1").Value = "Yes"
Else
    Range("C1").Value = "No"
End If

答案 2 :(得分:0)

这是一个on change sub(代码必须进入工作表模块)。它只会在您更改B列中的单元格时激活。

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target is Nothing Then Exit Sub
    If Target.Cells.Count > 1 Then Exit Sub
    If Target.Column <> 2 Then Exit Sub
    If Cells(Target.Row, 1).Value = Cells(Target.Row, 2).Value Then
        Cells(Target.Row, 3).Value = "Yes"
    Else
        Cells(Target.Row, 3).Value = "No"
    End If
End Sub

对于记录,这不使用按钮,但是当您手动将数据输入到Col B中的单元格时,它实现了计算两个单元格是否相等的目标。

答案 3 :(得分:0)

您可以在VBA中使用IIF功能。它类似于Excel IF

[c1] = IIf([a1] = [b1], "Yes", "No")

答案 4 :(得分:0)

Sub CompareandHighlight()
    Dim n As Integer
    Dim sh As Worksheets
    Dim r As Range

    n = Worksheets("Indices").Range("E:E").Cells.SpecialCells(xlCellTypeConstants).Count
    Application.ScreenUpdating = False 

    Dim match As Boolean
    Dim valE As Double
    Dim valI As Double
    Dim i As Long, j As Long

    For i = 2 To n
        valE = Worksheets("Indices").Range("E" & i).Value
        valI = Worksheets("Indices").Range("I" & i).Value

        If valE = valI Then

        Else:                           
            Worksheets("Indices").Range("E" & i).Font.Color = RGB(255, 0, 0)
        End If
    Next i

    Application.ScreenUpdating = True
End Sub