0

我正在尝试在 excel 中对齐/匹配未对齐的数据。目前数据如下:

customerid  customerid2 emailaddress          firstname         lastname

1           2           bobhope@.com          Chris             Anderson
2           1           chrisanderson@.com    Bob               Hope
7           8           Bryansmoth@.com       Jenn              Lacy
8           7           Jennlacy@.com         Bryan             Smoth
9                       123@.com
10          11          RonnieWilliams@.com   Andrew            Smoth
11          10          Andrewsmoth@.com      Ronnie            Williams

基本上,我试图让 A 列和 B 列的 ID 相应地匹配,并且所有数据都向右对齐。所以它变成:

1            1          bobhope@.com          Bob               Hope
2            2          chrisanderson@.com    Chris             Anderson
7            7          Bryansmoth@.com       Bryan             Smoth
8            8          Jennlacy@.com         Jenn              Lacy
9                       123@.com
10           10         RonnieWilliams@.com   Ronnie            Williams
11           11         Andrewsmoth@.com      Andrew            Smoth

我会手动执行此操作,但有 17,000 个错误条目。据我了解,我可以在 excel 中运行 VBA,这将有助于纠正这个问题。

4

1 回答 1

1

我通常不会这么快给出代码,但这似乎是一个有趣的问题。试试这个简单的代码。

我的假设

  1. 具有数据的工作表的名称称为Sheet1
  2. 数据在Columns A:E
  3. 没有多次出现customerid2
  4. 第 1 行有标题

逻辑

  1. 将范围存储B:E在数组中
  2. 清除B:E输出列
  3. 通过 col A 循环并将其与数组的 col 1 匹配,如果找到匹配项,则填充相关行

代码

我已经评论了代码。不过,如果您遇到问题,那么只需回帖即可。

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim MyData As Variant
    Dim i As Long, j As Long, lRow As Long

    '~~> This is your relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> get the last row which has data
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Get your Col B:E Range
        Set rng = ws.Range("B2:E" & lRow)

        '~~> Store the range in an array
        MyData = rng

        '~~> Clear Col B:E for output
        rng.ClearContents

        '~~> Loop through Col A
        For i = 2 To lRow
            '~~> Loop through Array
            For j = LBound(MyData) To UBound(MyData)
                '~~> If match found then write to relevant row
                If MyData(j, 1) = .Range("A" & i).Value Then
                    .Range("B" & i).Value = MyData(j, 1)
                    .Range("C" & i).Value = MyData(j, 2)
                    .Range("D" & i).Value = MyData(j, 3)
                    .Range("E" & i).Value = MyData(j, 4)
                    Exit For
                End If
            Next j
        Next i
    End With
End Sub

截图(之前和之后)

在此处输入图像描述

于 2013-09-27T10:46:17.517 回答