如何从单独的范围中提取唯一值并连接到同一范围上的相邻列(偏移量 (,-1))?

2024-03-08

I need to extract the unique values from a separate ranges and concatenate to the adjacent column (offset (,-1) on the same range.
As you see on the below picture, I sort my dataset by column_A ,so all duplicate values on column_A will be together.
I need to put the duplicate values on column_A with the respective cells on the same rows into a variable Range e.g rng1 = [A2:C4],
Then extract unique values found on rng1.columns(3) and concatenate to each cell on rng1.columns(2) ,range(“B2:B4”)
By the same rng2 will be = [A5:C7] and so on.
The problem is I do not know how when ID values is duplicates to put them and it’s adjacent cells on the same rows into a variable range and process it !
At end column C will be be deleted.
In advance, great thanks for your learning support. enter image description here

Sub Extract_unique_values_and_combine_in_adjacent_cells()
 
   Dim ws As Worksheet: Set ws = ActiveSheet
    Dim rng As Range
     Set rng = ws.Range("A2:C" & ws.Cells(Rows.Count, "A").End(xlUp).Row)
 
   Dim arr: arr = rng.Value2
    Dim i As Long
     For i = LBound(arr) To UBound(arr)
 
   On Error Resume Next 'skip error if i= 1
      If arr(i, 1) = arr(i + 1, 1) Or _
         arr(i, 1) = arr(i - 1, 1) Then
        arr(i, 2) = arr(i, 2) & vbLf & unique(ws.Range("C2:C4").Value2) 'I need (crg) to be dynamic
      End If
   On Error GoTo 0
 
    Next i
 
   rng.Value = arr
 
End Sub
 
Function unique(crg)
 
   Dim cel, a
     With CreateObject("scripting.dictionary")
       For Each cel In crg
         a = .Item(cel)
       Next
     unique = Join(.Keys, vbLf)
    End With
 
End Function

请尝试下一个代码。它使用字典和数组来保存、处理和返回必要的字符串。它将按任意顺序处理所有类别(A:A 中唯一):

Sub CombineRanges()
   Dim sh As Worksheet, lastR As Long, arr, arrDict, dict As Object
   Dim arrDB, arrDC, mtch, arrFin, i As Long, j As Long, k As Long
   
   Set sh = ActiveSheet
   lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
   
   arr = sh.Range("A2:C" & lastR).Value2
   Set dict = CreateObject("Scripting.Dictionary")
   
   For i = 1 To UBound(arr)
        If Not dict.Exists(arr(i, 1)) Then
            dict.Add arr(i, 1), Array(arr(i, 2), arr(i, 3)) 'place the strings from columns B and C
        Else
            arrDict = dict(arr(i, 1))                       'extract the array from dict items (it cnnot be modified inside the item)
            arrDict(0) = arrDict(0) & "|" & arr(i, 2)       'place in the array first element the strings collected from B:B
            arrDC = Split(arrDict(1), vbLf)                 'try splitting the second array element (string(s) from C:C)
            If UBound(arrDC) = 0 Then                       'if only one element:
                If arrDC(0) <> arr(i, 3) Then arrDict(1) = arrDict(1) & vbLf & arr(i, 3) 'add to it the value from C:C, separated by vbLf
            Else
                mtch = Application.match(arr(i, 3), arrDC, 0) 'check unicity of the string from C:C
                If IsError(mtch) Then                         'only if not existing:
                    arrDict(1) = arrDict(1) & vbLf & arr(i, 3)'add it to the string to be used in the next step
                End If
            End If
            dict(arr(i, 1)) = arrDict                         'put back the array in the dictionary item
        End If
   Next i

   ReDim arrFin(1 To UBound(arr), 1 To 2): k = 1              'redim the final array and initialize k (used to fill the array)
   For i = 0 To dict.count - 1                                'iterate between the dictionary keys/items:
        arrDict = dict.Items()(i)                             'place the item array in an array
        arrDB = Split(arrDict(0), "|")                        'obtain an array of B:B strins from the item first array element
        For j = 0 To UBound(arrDB)   'how many unique keys exists!
                arrFin(k, 1) = dict.Keys()(i)                 'place the dictionry key per each iteration
                arrFin(k, 2) = arrDB(j) & vbLf & arrDict(1)   'build the string of the second column
                k = k + 1
        Next j
   Next i
   'drop the processed result near the existing range (for easy visual comparison):
   sh.Range("D2").Resize(UBound(arrFin), 2).Value2 = arrFin
End Sub

上面的代码假设我在评论中写的内容在一段时间之前放置,并且您没有确认/确认...

Edited:

请测试下一个版本。它将仅返回保留连接的 B:C 列值的列,并跳过 C:C 中的空值(如果是这种情况)。它也将在 D:D 中回归。测试后,如果它满足您的需要,只需将最后一行代码中的“D”更改为“B”即可:

Sub CombineRangesOneColumn()
   Dim sh As Worksheet, lastR As Long, arr, arrDict, dict As Object
   Dim arrDB, arrDC, mtch, arrFin, i As Long, j As Long, k As Long
   
   Set sh = ActiveSheet
   lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
   
   arr = sh.Range("A2:C" & lastR).Value2
   Set dict = CreateObject("Scripting.Dictionary")
   
   For i = 1 To UBound(arr)
        If Not dict.Exists(arr(i, 1)) Then
            dict.Add arr(i, 1), Array(arr(i, 2), arr(i, 3)) 'place the strings from columns B and C
        Else
            arrDict = dict(arr(i, 1))                                   'extract the array from dict items (it cnnot be modified inside the item)
            arrDict(0) = arrDict(0) & "|" & arr(i, 2)        'place in the array first element the strings collected from B:B
            arrDC = Split(arrDict(1), vbLf)                      'try splitting the second array element (string(s) from C:C)
            If UBound(arrDC) = 0 Then                           'if only one element:
                If arrDC(0) <> arr(i, 3) Then arrDict(1) = arrDict(1) & IIf(arr(i, 3) = "", "", vbLf & arr(i, 3)) 'add to it the value from C:C, separated by vbLf
            Else
                mtch = Application.match(arr(i, 3), arrDC, 0) 'check unicity of the string from C:C
                If IsError(mtch) Then                                          'only if not existing:
                    arrDict(1) = arrDict(1) & IIf(arr(i, 3) = "", "", vbLf & arr(i, 3))       'add it to the string to be used in the next step
                End If
            End If
            dict(arr(i, 1)) = arrDict                                             'put back the array in the dictionary item
        End If
   Next i

   ReDim arrFin(1 To UBound(arr), 1 To 1): k = 1            'redim the final array and initialize k (used to fill the array)
   For i = 0 To dict.count - 1                                                'iterate between the dictionary keys/items:
        arrDict = dict.Items()(i)                                               'place the item array in an array
        arrDB = Split(arrDict(0), "|")                                      'obtain an array of B:B strins from the item first array element
        For j = 0 To UBound(arrDB)   'how many unique keys exists!                     'place the dictionry key per each iteration
                arrFin(k, 1) = arrDB(j) & vbLf & arrDict(1)       'build the string of the second column
                k = k + 1
        Next j
   Next i
   'drop the processed result near the existing range (for easy visual comparison):
   sh.Range("D2").Resize(UBound(arrFin), 1).Value2 = arrFin
End Sub
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从单独的范围中提取唯一值并连接到同一范围上的相邻列(偏移量 (,-1))? 的相关文章

  • Excel 2007 从 C# get_Value 始终返回 -2146826265

    我有一个引用 Microsoft Excel 12 0 对象库的小型 C 应用程序 除此之外 它还从 Excel 单元格读取值 它从一些较旧的 Excel xls 文件和一些 2007 文件 xlsx 中读取此值 所有 xls 文件的值都会
  • 索引行和列意外结果

    我试图理解以下行为 如果我有以下数据 A B a 1 b 2 c 3 如果我使用 INDEX A 1 B 3 它将正确显示整个范围 如果我使用 INDEX A 1 B 3 1 它将正确显示两列第一行的数据 如果我使用 INDEX A 1 B
  • Java 泛型从类创建数组

    我有一个层次结构 其中正方形 三角形和圆形都从形状延伸 我有一个工作方法 public void someMethod File file new File File with squares ThirdPartyClass foo new
  • 如何发布数组多维角度js

    我在 angularjs 中有一个数组 示例如下 scope order qty 20 scope order adress Bekasi scope order city Bekasi 这个数组可以用这个代码发布 http method
  • 使用图表时避免使用“激活”和“选择”(Excel)

    我知道使用Activate and Select在 Excel 中 VBA 不是最佳实践 我看过有关如何在处理范围时避免它们的参考资料 例如 LINK https stackoverflow com questions 10714251 e
  • 如何打印数组中每个单词之间的空格

    我记得在 w3school 上看到过一个函数 你可以打印出数组的所有单词并在它们之间添加一个空格 但无论我如何谷歌我都找不到它 其外观示例 function printWords var array Car Bus Motorcykle p
  • QByteArray 到整数

    正如您可能从标题中看出的那样 我在转换QByteArray为一个整数 QByteArray buffer server gt read 8192 QByteArray q size buffer mid 0 2 int size q siz
  • 将数组转换为具有默认值的对象的更简洁方法? (洛达什可用)

    我有一个数组 比如说 a b c 我想将其转换为一个对象 该对象以数组值作为键和我可以设置的默认值 所以如果默认值是true 我希望我的输出是 a true b true c true 下面的代码是否有更简洁的版本来实现此目的 var my
  • 如何使用 jQuery 通过 Ajax 发送复选框数组的值?

    我有一个包含很多表单字段的表单 12 x n 行 每行中的第一个字段 代表产品 是一个类似于以下内容的复选框
  • Office 365 中 Excel 中 Power Pivot 的计算列中正确的 DAX GROUPBY 语法是什么

    将以下语法输入到下面在 Excel Office 365 版本 的 powerpivot 中提供的表 Visits 的计算列公式中 GROUPBY Visits Patient Name First Visit Date MINX CURR
  • WordPress 中的 add_action 函数

    嗯 我正在学习创建一个 WordPress 插件 我下载了一个并阅读了代码 然后我看到了这个 我假设 foo 是它将添加操作的标签 但是 array 到底是做什么的呢 add action foo array foo1 foo2 我在看ht
  • JavaScript 中最长的通用前缀

    我正在尝试解决 Leet Code 挑战14 最长公共前缀 https leetcode com problems longest common prefix 编写一个函数来查找字符串数组中最长的公共前缀字符串 如果没有公共前缀 则返回空字
  • 从Excel单元格中提取固定长度的数字

    一些类似名称的线程 但仍然无法解决我的问题 我需要从 Excel 字符串中提取固定长度的 NUMBER 值 在我的场景中为 8 位数字 为此目的提供了以下 Excel 公式 MID A1 FIND SUBSTITUTE SUBSTITUTE
  • 使用 Excel VBA 循环工作簿文件夹并将所有工作表导出为制表符分隔文本

    我拼凑了一个 Excel VBA 脚本 该脚本将打开的工作簿中的所有工作表写入单独的制表符分隔文件 这仍然是 宏 吗 我正在 Excel 真空中学习这一点 它一次只处理一本工作簿 效果很好 这里是 Sub exportSheetsToTex
  • 如何从数组中提取特定元素?

    如果我有一个数组a 1 2 3 4 5 6 7 8 9 10 我想要这个数组的一个子集 第 1 个 第 5 个和第 7 个元素 是否可以通过简单的方式从该数组中提取这些内容 我在想这样的事情 a 0 4 6 1 5 7 但这行不通 还有一种
  • 有没有办法使用 Python Pandas 读取所有行,直到遇到空行

    我在 Excel 中有很多行 并且这些行在空行之后填充有垃圾值 有没有办法使用 Python pandas 只读取 Excel 中第一个空行之前的记录 我不知道 read excel 是否可以做到这一点 如果您从 Excel 导入空行 这些
  • 将数据从 R 导出到 Excel

    我试图将从 R 获得的一些结果导出到 Excel 中 但未成功 我尝试过以下代码 write table ALBERTA1 D ALBERTA1 txt sep t write csv ALBERTA1 ALBERTA1 csv your
  • 最小化代表性整数的误差之和

    Given n integers between 0 10000 as D1 D2 Dn where there may be duplicates and n can be huge I want to find k distinct r
  • 勾选或取消勾选复选框时输入时间戳

    我有一个 3 行 7 列的工作表 A1 G3 A 和 B 列有 6 个复选框 A1 B3 A 列和 B 列中的框分别链接到 C 列和 D 列 E 列和 F 列中的单元格只是分别复制 C 列和 D 列 实时E1细胞是 C1 and F3细胞是
  • Javascript 数组到 VBScript

    我有一个使用 Javascript 构建的对象数组 我需要使用 VBScript 读取它 如下例所示 我找不到在 VbScript 代码中循环遍历数组的方法myArray object 这个例子是我的问题的简化 我无法更改页面的默认语言 这

随机推荐