[英]compare 2 cells in excel by using vba
I would like to compare 2 cells' value and see whether they are match or not. 我想比较2个单元格的值,看看它们是否匹配。 I know how to do it on excel but I dont' know how to put it vba code. 我知道如何在excel上执行此操作,但我不知道如何将其放入vba代码。
Input & output: 输入输出:
Excel formula: Excel公式:
=IF(A1=B1,"yes","no")
Give this a try: 试试看:
Sub CompareCells()
If [a1] = [b1] Then
[c1] = "yes"
Else
[c1] = "no"
End If
End Sub
Assign this code to the button. 将此代码分配给按钮。
If (Range("A1").Value = Range("B1").Value) Then
Range("C1").Value = "Yes"
Else
Range("C1").Value = "No"
End If
Here is an on change Sub (code MUST go in the sheet module). 这是一个变化中的Sub(代码必须在工作表模块中)。 It will only activate if you change a cell in column B. 仅当您更改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
For the record, this doesn't use a button, but it accomplishes your goal of calculating if the two cells are equal any time you manually enter data into cells in Col B. 作为记录,它不使用按钮,但是它可以实现您每次在Col B中的单元格中手动输入数据时计算两个单元格是否相等的目标。
You can use the IIF function in VBA. 您可以在VBA中使用IIF函数。 It is similar to the Excel IF 它类似于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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.