我在excel中有两个单元格,它们包含用逗号分隔的数字串,我需要找到单元格1中但不在单元格2中的数字。我可以对列进行文本然后执行vlookup但是有更有效的方法吗?
单元格1:360,370,400,420 单元格2:400,420
答案:360,370
答案 0 :(得分:4)
您可以制作自定义功能来执行此操作。放在一个普通的代码模块中,然后你可以在工作表上调用它,如:
=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
注意:这假设单元格包含 text 格式的数字,否则取决于用户本地,400,420
之类的值实际上意味着Four-hundred thousand four-hundred & twenty
<强>更新强>
一个简单的函数也可以做文本到列的事情。选择单个单元格,然后运行此宏。如果目标单元格中已存在任何数据,则可能会覆盖数据(无警告)。
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