vba:查找文本中不存在的数字

我在Excel中有两个单元格,它们包含以逗号分隔的数字string,我需要find单元格1中存在的数字,但不是单元格2中的数字。我可以对列进行文本操作,然后进行查找,但还有更多有效的方法来做到这一点?

小区1:360,370,400,420小区2:400,420

答案:360,370

你可以做一个自定义函数来做到这一点。 放在一个普通的代码模块中,然后你可以在工作表上调用它:

=GetUniques(A1,B1) ,它应该返回唯一值。

 Function GetUniques(ByVal cell1 As Range, ByVal cell2 As Range, Optional reverse As Boolean = False) As Variant 'compares text strings of delimited numbers in two separate excel cells ' returns unique values from cell1 by default ' to return results from cell2 instead, use optional reverse=True Dim v As Variant Dim varValues As Variant Dim result As String If cell1.Cells.Count > 1 Or cell2.Cells.Count > 1 Then GetUniques = CVErr(xlErrRef) GoTo EarlyExit End If varValues = Split(cell1.Value, ",") For Each v In varValues v = Trim(v) If Not reverse Then If InStr(1, cell2.Value, v) = 0 Then result = IIf(result = vbNullString, v, result & "," & v) End If Else: If InStr(1, cell2.Value, v) > 0 Then result = IIf(result = vbNullString, v, result & "," & v) End If End If Next If Len(result) = 0 Then result = "No matches" GetUniques = result EarlyExit: End Function 

注意:这假定单元格包含文本格式的数字,否则取决于本地用户,像400,420这样的值其实意味着Four-hundred thousand four-hundred & twenty

更新

一个简单的函数也可以做文本到列的东西。 select一个单元格,然后运行此macros。 这可能会覆盖数据(没有警告),如果有任何已经在目标单元格中​​。

 Sub SplitTextToColumns() If Selection Is Nothing Then Exit Sub Dim cl As Range Dim varValues As Variant Dim i As Long Set cl = Selection.Cells(1) varValues = Split(cl, ",") If UBound(varValues) < 0 Then Exit Sub cl.Resize(1, UBound(varValues) + 1).Value = varValues End Sub