![](/img/trans.png)
[英]Compare 2 cells in excel using VBA for SAP GUI scripting
[英]compare 2 cells in excel by using vba
我想比較2個單元格的值,看看它們是否匹配。 我知道如何在excel上執行此操作,但我不知道如何將其放入vba代碼。
輸入輸出:
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(代碼必須在工作表模塊中)。 僅當您更改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中的單元格中手動輸入數據時計算兩個單元格是否相等的目標。
您可以在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.