excel多列匹配

时间:2017-07-27 18:53:22

标签: excel vba excel-vba

我在excel中有以下类型的数据:

Col 1       Col 2       Col 3
a           Apple       x & y & z
a           Ant         x & y & z
a           Aeroplane   x & y & z
b           Ball        m & n
b           Bat         m & n
c           Cat         k & l
c           Carrom      k & l
c           Can         k & l

我想在第3列中按&分隔/拆分值字符,然后为每个值创建其他行。类似下面的结果应该是结果:

Col 1       Col 2       Col 3
a           Apple       x
a           Apple       y
a           Apple       z
a           Ant         x
a           Ant         y
a           Ant         z
a           Aeroplane   x
a           Aeroplane   y
a           Aeroplane   z
b           Ball        m
b           Ball        n

我使用的值只是样本实际数据包含由&分隔的单词。在第3栏

adding image since formating getting messed up for table

2 个答案:

答案 0 :(得分:0)

因为它是一次性的'我会做一个手动修复

将第3列中只有一个项目的所有行放入新工作表中。 把两件物品放在另一张纸上 等等 然后,去掉两个项目表上的第一个项目并将其复制到第一个工作表中 然后去掉两个项目表上的第二个项目并将其复制到第一个工作表中。 继续前进,最终您可以获得所需的数据。

虽然这需要很长时间,但它可能比学习VBA更快,并且编写例程来执行此操作。

答案 1 :(得分:0)

此代码将执行您对所提供信息的意图。我鼓励你查找使用的方法,因为它们非常基础,并且难度很高。我已经写下了解释每个部分正在做什么的评论。 GL

Sub test()
Dim filter, C1, C2 As String
Dim counter As Integer
Dim letters() As String
Dim i, x As Integer
Dim char As String

Cells(1, 3).Select
x = 1

'Checks to see if the third column is blank, if not it will continue
While Cells(x, 3).Value <> ""

'Re instantiates an array of size 3 to store the letters (technically 4 since 0 is also a position) Also erases past stored data
ReDim letters(3) As String
i = 0
'Filter stores the whole string
filter = ActiveCell.Value

'Stores the column A and B values  of that row in C1 and C2
C1 = ActiveCell.Offset(, -2).Value
C2 = ActiveCell.Offset(, -1).Value

'This for loop goes through each character of filter string
For counter = 1 To Len(filter)
'char stores the character
char = Mid(filter, counter, 1)
    If char = " " Or char = "&" Then
    Else:
    'stores any character not blank and "&" in an array
    letters(i) = char
    i = i + 1
    End If
Next

'If statement to skip rows that only have 1 letter
If letters(1) <> Empty Then

'For loop that will create a new line and print out array letters in each new row
For i = 0 To 1
ActiveCell.Value = letters(i)
  ActiveCell.Offset(1).EntireRow.Insert
  ActiveCell.Offset(1).Select
  ActiveCell.Offset(, -2).Value = C1
  ActiveCell.Offset(, -1) = C2
  ActiveCell.Value = letters(i + 1)
Next i
End If
x = x + 1
ActiveCell.Offset(1).Select

Wend
End Sub