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

compare 2 cells in excel by using vba

我想比较 2 个单元格的值,看看它们是否匹配。 我知道如何在 excel 上执行此操作,但我不知道如何输入 vba 代码。

输入&输出:

  1. 单元格 A1 的值已经在 excel。
  2. 在单元格 B1 中手动输入一个值。
  3. 单击 button_click 子项以查看 2 个单元格上的值是否相同。
  4. 在单元格 C1
  5. 上显示 "Yes" 或 "No"

Excel公式:

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

试一试:

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

将此代码分配给按钮。

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

这是一个正在更改的 Sub(代码必须放在 sheet 模块中)。它只会在您更改 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

郑重声明,这不使用按钮,但它可以实现您的目标,即在您手动将数据输入列 B 中的单元格时计算两个单元格是否相等。

您可以使用VBA中的IIF函数。它类似于 Excel IF

[c1] = IIf([a1] = [b1], "Yes", "No")
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