首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从D列中提取唯一值,并在单个单元格中合并。Excel VBA

从D列中提取唯一值,并在单个单元格中合并。Excel VBA
EN

Stack Overflow用户
提问于 2021-05-21 21:33:55
回答 1查看 170关注 0票数 1

我在(D)栏中有重复的值。

如何从D列中提取唯一值,并在不丢失数据的情况下使用vba组合成单个单元格(H1)

例如:"J10P,G345,R1,J10G“

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-21 23:17:09

连接唯一值(字典)

  • 调整常量部分和工作簿中的值。

代码语言:javascript
复制
Option Explicit

Sub concatUnique()
    
    Const sName As String = "Sheet1"
    Const sFirst As String = "D1"
    
    Const dName As String = "Sheet1"
    Const dFirst As String = "H1"
    Const dDelim As String = ", "

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    ' Create a reference to the Source Range.
    Dim srg As Range
    Dim srCount As Long
    With wb.Worksheets(sName).Range(sFirst)
        Dim lCell As Range
        Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
            .Find("*", , xlFormulas, , , xlPrevious)
        If lCell Is Nothing Then Exit Sub
        srCount = lCell.Row - .Row + 1
        Set srg = .Resize(srCount)
    End With

    ' Write values from Source Range to Source Data Array.
    Dim sData As Variant
    If srCount = 1 Then
        ReDim sData(1 To 1, 1 To 1): sData(1, 1) = srg.Value
    Else
        sData = srg.Value
    End If
    
    ' Write unique values from Source Data Array to Unique Dictionary.
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare
    Dim Key As Variant
    Dim r As Long
    For r = 1 To UBound(sData, 1)
        Key = sData(r, 1)
        If Not IsError(Key) Then
            If Len(Key) > 0 Then
                dict(Key) = Empty
            End If
        End If
    Next r
    
    If dict.Count > 0 Then
        ' Create a reference to the Destination Cell (Range).
        Dim dCell As Range: Set dCell = wb.Worksheets(dName).Range(dFirst)
        ' Write the unique values from Unique Dictionary to Resulting String.
        Dim Result As String: Result = Join(dict.Keys, dDelim)
        ' Write the result to the Destination Cell (Range).
        dCell.Value = Result
        ' or in one line:
        'wb.Worksheets(dName).Range(dFirst).Value = Join(dict.Keys, dDelim)
    End If
    
End Sub
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67644069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档