我有一张excel表,其中包含以下两种格式的数据:
Category1 Sub-category1
Category1 Sub-category2
Category2 Sub-category1
Category2 Sub-category2
Category2 Sub-category3
等等。一个类别下的子类别数量不相同,因此某些类别有2个子类别,而有些类别有15个。 我希望输出格式为:
Category1子类别1子类别2
类别2子类别1子类别2子类别3
现在我已经在第三列的类别中添加了子类别的数量,并运行以下代码(取自互联网)
Sub Trans()
Dim rng As Range
Dim I As Long
Dim rng2 As Range
Dim x As Long
Set rng = Range("b1")
Set rng2 = Range("C1")
While rng.Value <> ""
I = I + 1
x = rng2.Value
rng.Resize(x).Copy
Range("E" & I).PasteSpecial Transpose:=True
Set rng = rng.Offset(x)
Wend
End Sub
问题是我无法获得所需的结果,因为我无法更改x的值以反映特定类别中子类别的数量。任何有关此代码的帮助或实现此目的的新方法将不胜感激。 感谢
答案 0 :(得分:1)
Sub Trans()
Dim rng As Range
Dim x As Long, y As Long
Dim category As String
Set rng = Range("B1")
Set rng2 = Range("C1")
For Each rng In Range("B1", Range("B1").End(xlDown))
If rng <> category Then
category = rng.Value
y = 0
x = x + 1
Range("E1").Offset(x - 1, y) = category
End If
y = y + 1
Range("E1").Offset(x - 1, y) = rng.Offset(0, 1)
Next
End Sub