在excel vba中比较string

我有一串由字符“A”,“B”…“Z”(而不是其他人)组成的string。 一个典型的string看起来像ABZYC 。 string像ABCABDC一样给我。 如果一个string包含在另一个string中(即两个string中的任何一个包含另一个string的所有字母),string是可比的。 string出现的顺序无关紧要。

在excel vba中有没有直接的function呢?

例子:
ACBDACMatch
ACBDCAMatch
ACBDADBMatch
ACABCDMatch
ABCABDNo Match

在工作簿的模块中添加以下function:

 Function allIn(str1, str2) ' check whether all elements of str1 occur in str2 ' and vice versa Dim l1, l2, ii As Integer Dim isfound As Boolean isfound = True l1 = Len(str1) l2 = Len(str2) If l1 < l2 Then ' look for all the elements of str1 in str2 For ii = 1 To l1 If InStr(1, str2, Mid(str1, ii, 1), vbTextCompare) <= 0 Then isfound = False Exit For End If Next ii Else ' look for all the elements of str2 in str1 For ii = 1 To l2 If InStr(1, str1, Mid(str2, ii, 1), vbTextCompare) <= 0 Then isfound = False Exit For End If Next ii End If allIn = isfound End Function 

现在,您可以使用result = inStr("ABD", "BAD")或从电子表格本身调用代码中的其他位置。 在电子表格上,您可以键入=allIn(A3, B6)来比较单元格A3B6string。

这是当我这样做(我在单元格C1input=allIn(A1, B1) ,然后将公式拖动到接下来的四行):

电子表格的屏幕截图

我相信解决你的问题。

编辑:我只是注意到@菲利普对你的问题的评论 – 我似乎已经实施了他的build议,虽然我没有看到它,当我开始撰写它的时候…但是这里有一个帽子的提示!

INSTR将在string中find一个子string:

 Typical_String = "ABZYC" if instr(Typical_String,"ABC") > 0 then 

如果你想要一个公式解决scheme,在Excel论坛网站上的一个叫Schielrn的用户提出了这个崇高的杰作 (使用ARRAY FORMULAS

或者,如果你想要一个VBA,试试这个…

 Sub compare() Dim iIndx As Integer Dim str1 As String Dim str2 As String Dim sLetter As String Dim bFound As Boolean Range("A1").Select bFound = False Do str1 = VBA.Trim(ActiveCell.Text) str2 = VBA.Trim(ActiveCell.Offset(0, 1).Text) For iIndx = 1 To Len(str1) If VBA.InStr(str2, VBA.Mid(str1, iIndx, 1)) <> "" Then ' found it bFound = True Else bFound = False exit for End If Next If bFound = False Then ' check the other way! For iIndx = 1 To Len(str2) If VBA.InStr(str1, VBA.Mid(str2, iIndx, 1)) <> "" Then ' found it bFound = True Else bFound = False exit for End If Next End If If bFound = True Then ActiveCell.Offset(0, 2).Value = "MATCHED!" ActiveCell.Offset(1, 0).Select Loop While Not ActiveCell.Offset(1, 0).Text = "" End Sub 

我错过了这个post!

使用functionEXACT

比较两个文本string,如果它们完全相同则返回TRUE,否则返回FALSE。 EXACT区分大小写,但忽略格式差异。

我通常添加functionUPPER即:

 A1 = Some Place B1 = some place 

 =EXACT(UPPER(A1),UPPER(B1)) = EXACT(SOME PLACE, SOME PLACE) = TRUE 

没有UPPER

 =EXACT(A1,B1) = EXACT(Some Place, some place) = FALSE