Excel - 自动填充/编号与列和行之间的自定义模式,同时允许重复?

时间:2017-06-22 00:50:16

标签: excel vba excel-vba

我的数据与此类似,其中我在B,D和F栏中的值可能会偶尔重复:

select cars from table group by cars having count(cars) = 4 

我需要做的是自动填充/编号A,C和E列,首先在工作表上水平然后垂直移动,使用自定义模式 - 基本上为列B,D和F中的数据提供唯一ID。

在这样做时,我需要记住以下几点:

  1. 列B,D和F中的重复值未分配新ID,但会收到先前分配的ID。
  2. B列将始终包含数据,因此我希望填充A列的所有行。
  3. 列D和F可能并不总是有数据。
    • 因此,如果D列包含数据,我只希望填充C列中的行。
    • 同样,如果列F包含数据,我只希望填充E列中的行。
  4. 我期望达到的最终结果是:

     Column A     Column B     Column C     Column D     Column E     Column F
     --------     --------     --------     --------     --------     --------
                  Data1                     Data2                     Data3   
                  Data4                     Data1                                         
                  Data5                                               Data1
                  Data3
    

    不幸的是,我的纸张非常长,已经达到近千种,这使得手动编号很困难。如果我需要在中间引入额外的行,我基本上最终会从那一点开始打破序列,并且必须一次又一次地开始编号直到结束。

    我试过搜索内置公式和vba代码,但我找不到适合我问题的东西。求救!

1 个答案:

答案 0 :(得分:0)

请试一试。它利用一个Dictionary,它在B,D,F列中存储先前识别的数据字符串。

Sub BreadthSearchFirst()

Dim dict
Set dict = CreateObject("Scripting.Dictionary")

Dim sht1 As Worksheet
Set sht1 = ActiveWorkbook.ActiveSheet

Dim ID, newID, key As String
Dim j, i, count As Integer

ID = "UR"
count = 1

'include the starting and last row number
startrow = 1
totalrow = 100

'loop over each row
For j = startrow To totalrow
    'loop over each column
    For i = 1 To 6
        'looks only in even columns
        If i Mod 2 = 0 Then
            'Checks if a Value is Present
            If sht1.Cells(j, i) <> "" Then
                'assigns the value as a key if the cell is not empty
                key = sht1.Cells(j, i)
                'checks if the key is present in the dictionary
                If dict.Exists(key) Then
                    'call the previously stored data if it exists
                    sht1.Cells(j, i - 1) = dict.Item(key)
                Else
                    'places the newID in the odd column
                    newID = ID & count
                    sht1.Cells(j, i - 1) = (ID & count)
                    'creates a new key within the dictionary
                    dict.Add key, newID
                    'increment the ID count
                    count = count + 1
                End If
            End If
       End If

    Next i
Next j

End Sub

有几点需要注意 如果列不是前6列(即A到F),则需要进行更改 修改起始行和结束行,可以使用方法找到工作表中的最后一行,并可以相应地替换它。偶数列(B,D,F)中不应有任何空格,如果是这样,它会将其识别为数据。

祝你好运!