使用VBA

时间:2017-01-28 18:06:30

标签: excel vba excel-vba

我想将以下数据从其垂直状态移动到水平数据。我想在VBA中找到解决方案。

| abc.com  | result 1
| abc.com  | result 2
| abc.com  | result 3
| xyz.com  | result 1
| xyz.com  | result 2
| xyz.com  | result 3

我想将其解析为

| abc.com  | result 1 | result 2 | result 3
| xyz.com  | result 1 | result 2 | result 3 | result 4

提前致谢

1 个答案:

答案 0 :(得分:0)

这很容易!只需执行文本到列,即可正确设置数据。也许你的身体是正确的;你提出的同样看起来有点怪异。无论如何,在A1:B6我有这个。

 abc.com     result 1
 abc.com     result 2
 abc.com     result 3
 xyz.com     result 1
 xyz.com     result 2
 xyz.com     result 3

然后,只需运行下面的脚本。

Sub ConcatData()
Dim X As Double
Dim DataArray(5000, 2) As Variant
Dim NbrFound As Double
Dim Y As Double
Dim Found As Integer
Dim NewWks As Worksheet

Cells(1, 1).Select
Let X = ActiveCell.Row
Do While True
If Len(Cells(X, 1).Value) = Empty Then
Exit Do
End If
If NbrFound = 0 Then
NbrFound = 1
DataArray(1, 1) = Cells(X, 1)
DataArray(1, 2) = Cells(X, 2)
Else
For Y = 1 To NbrFound
Found = 0
If DataArray(Y, 1) = Cells(X, 1).Value Then
DataArray(Y, 2) = DataArray(Y, 2) & ", " & Cells(X, 2)
Found = 1
Exit For
End If
Next
If Found = 0 Then
NbrFound = NbrFound + 1
DataArray(NbrFound, 1) = Cells(X, 1).Value
DataArray(NbrFound, 2) = Cells(X, 2).Value
End If
End If
X = X + 1
Loop

Set NewWks = Worksheets.Add
NewWks.Name = "SummarizedData"
Cells(1, 1).Value = "Names"
Cells(1, 2).Value = "Results"
X = 2
For Y = 1 To NbrFound
Cells(X, 1).Value = DataArray(Y, 1)
Cells(X, 2).Value = DataArray(Y, 2)
X = X + 1
Next
Beep
MsgBox ("Summary is done!")
End Sub

请确保您有一张名为" SummarizedData"!

的工作表