在excel VBA中将两个不同列的值与唯一条件进行比较

时间:2017-09-23 14:55:00

标签: excel vba excel-vba

我正在尝试比较两个不同列的值。

Image

所以有两种情况: -

  1. 在“A”列中,存在一个两位数的值,这将导致“B”列中的七位数值。
  2. 在“A”列中,存在一个三位数的值,这将导致“B”列中的八位数值。
  3. 我想验证'B2'和'B3'是否分别以14和21开头,如果没有Msgbox'行号错误'。 如果没有Msgbox'行号错误',则'B3'和'B4'分别以109和289开头。

3 个答案:

答案 0 :(得分:2)

我会使用UDF。输入这是一个标准模块:

Public Function IsItGood(r1 As Range, r2 As Range) As String
    Dim v1 As String, v2 As String, L As Long
    v1 = r1.Text
    v2 = r2.Text
    L = Len(v1)
    If v1 = Left(v2, L) Then
        IsItGood = "Noerror"
    Else
        IsItGood = "Error in this row"
    End If
End Function

然后在 C2 中输入:

=isitgood(A2,B2)

并复制下来:

enter image description here

答案 1 :(得分:1)

你可以尝试一下......

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

答案 2 :(得分:1)

将此公式放入C2并复制下来:

=IF(AND(LEN(SUBSTITUTE(B2,A2,""))=5,FIND(A2,B2&A2)=1),"No Error","Error")

enter image description here

要获取不起作用的行号列表,可以使用以下公式:

=AGGREGATE(15,6,ROW($A$2:$A$7)/((--LEFT($B$2:$B$7,LEN($A$2:$A$7))<>$A$2:$A$7)+(LEN($B$2:$B$7)-LEN($A$2:$A$7)<>5)>0),ROW(1:1))

将它放在第一个单元格中,然后复制/粘贴,直到用完了有错误的行。

enter image description here