1

我在 excel 中有两个单元格,它们包含用逗号分隔的数字字符串,我需要找到单元格 1 中存在但单元格 2 中不存在的数字。我可以对列进行文本处理,然后进行 vlookup,但还有更多有效的方法来做到这一点?

单元格 1:360,370,400,420 单元格 2:400,420

答案:360,370

4

1 回答 1

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

注意:这假设单元格包含文本格式的数字,否则取决于用户本地,一个值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
于 2013-09-19T15:53:33.523 回答