从Col1和Col2中的文本在Col3中写入不匹配的数据

时间:2019-08-12 07:45:06

标签: excel vba

我有2组数据,一组是带有修订的零件编号列表(有些没有修订),而没有修订的相同零件列表。这些是管理员多年来手动输入的,现在我需要创建一组数据,即零件号,修订版。

由于过去发生的任何精神错乱,修订可能会出现在零件号中的随机点上,每次我这么说我都会感到不寒而栗!

因此,我需要一次将一个字符串的字符串1与字符串2进行比较,并用差异填充临时字符串。字符串1将带有修订版本,字符串2将不带有修订版本,并且由于人为错误,字符串2可能不仅仅是省略了修订版本,因此需要显示这些内容以进行手动检查。

我发现了一些接近的内容,但是我对VBA的了解不足以让我继续前进。

Function WORDDIF(rngA As Range, rngB As Range) As String

Dim WordsA As Variant, WordsB As Variant
Dim ndxA As Long, ndxB As Long, strTemp As String

WordsA = Split(rngA.Text, " ")
WordsB = Split(rngB.Text, " ")

For ndxB = LBound(WordsB) To UBound(WordsB)
    For ndxA = LBound(WordsA) To UBound(WordsA)
        If StrComp(WordsA(ndxA), WordsB(ndxB), vbTextCompare) = 0 Then
            WordsA(ndxA) = vbNullString
            Exit For
        End If
    Next ndxA
Next ndxB

For ndxA = LBound(WordsA) To UBound(WordsA)
    If WordsA(ndxA) <> vbNullString Then strTemp = strTemp & WordsA(ndxA) & " "
Next ndxA

WORDDIF = Trim(strTemp)

End Function

我希望可以比较一下字符串中的每个字母,一旦在字符串2中发现不匹配,就会用该不匹配填充修订字符串。比较将继续在字符串1的相同字母上进行,直到在字符串2中找到匹配项为止。例如:

String 1 = 123-2A3-456
String 2 = 123-23-456
Revision = A

String 1 = 123-2A3-456
String 2 = 123-23-46
Revision = A5

1 个答案:

答案 0 :(得分:2)

类似的东西吗?

Function WORDDIF(rngA As Range, rngB As Range) As String

Dim WordsA As Variant, WordsB As Variant
Dim ndxA As Long, ndxB As Long, strTemp As String

Dim a As Integer
Dim b As Integer

a = Len(rngA.Text)
b = 1
txt = ""

For i = 1 To a

    If Mid(rngA.Text, i, 1) = Mid(rngB.Text, b, 1) Then
        b = b + 1
    Else
        txt = txt & Mid(rngA.Text, i, 1)
    End If

Next


WORDDIF = txt

End Function

演示:

enter image description here

注意:它将仅将第一个字符串与第二个字符串进行比较,无反之。如果这是您的要求,则可以相应地操作当前代码。