[英]comparing values of two different columns with a unique condition in excel VBA
我正在尝试比较两个不同列的值。
所以有两种情况:
如果没有Msgbox'行号错误',我想验证'B2'和'B3'是否分别以14和21开头。 如果没有Msgbox“行号错误”,则“ B3”和“ B4”是否分别以,109和289开头。
您可以尝试一下...
Sub CompareColumns()
Dim lr As Long, n As Long
Dim rng As Range, cell As Range
Dim strA As String, strB As String, str As String
Dim NotMatched As Boolean
lr = Cells(Rows.Count, 1).End(xlUp).Row
'Assuming your data starts from Row2
Set rng = Range("B2:B" & lr)
str = "The following cells don't match." & vbNewLine & vbNewLine
For Each cell In rng
If cell <> "" Then
n = Len(cell.Offset(0, -1))
If n > 0 Then
strA = cell.Offset(0, -1).Text
strB = Left(cell, n)
If strA <> strB Then
NotMatched = True
str = str & cell.Offset(0, -1).Address(0, 0) & " : " & cell.Offset(0, -1).Value & vbTab & cell.Address(0, 0) & " : " & cell.Value & vbNewLine
End If
Else
str = str & cell.Offset(0, -1).Address(0, 0) & " : " & cell.Offset(0, -1).Value & vbTab & cell.Address(0, 0) & " : " & cell.Value & vbNewLine
End If
End If
n = 0
strA = ""
strB = ""
Next cell
If NotMatched Then
MsgBox str, vbInformation
Else
MsgBox "Both columns match.", vbInformation
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.