我有一长串联系方式详细信息,这些详细信息被组织成 2 列上的 block ,如下所示:
A B
Name John
Country USA
Phone 1234
Email j@hotmail.com
Name John
Country USA
Phone 1234
Name John
Country USA
我想像这样组织它们:
Name Country Phone Email
John USA 1234 j@hotmail.com
John USA 1234
John USA
如果 block 的长度都相同(即全部有 4 行),那么使用过滤器按 col1 名称进行选择并复制到新列会很容易,但是您会注意到有时电子邮件、电话等会丢失,因此每个联系人的总 block 长度不相同,因此在过滤到新列后它们不会对齐。
一种方法是使用“名称”作为每个 block 应该转置的起点和终点来转置每个 block ,但我不确定如何进行。也许有更简单的方法?
我怎样才能最好地解决这个问题?
最佳答案
Option Explicit
Sub transpose()
'This code assumes "Name", "Country", "Email" and "Phone" are spelled the same for each 'block', case not important
Dim wks As Worksheet
Dim i As Integer
Dim lastRow As Integer
Dim outRowCounter As Integer
Dim heading As String
Set wks = Worksheets("Sheet1")
lastRow = wks.Range("A65536").End(xlUp).Row
outRowCounter = 1
'assumes the output colums are Name = 5, Country = 6, Phone = 7, Email = 8
For i = 1 To lastRow
If LCase(wks.Cells(i, 1).Value) = "name" Then
outRowCounter = outRowCounter + 1
wks.Cells(outRowCounter, 5).Value = wks.Cells(i, 2).Value
ElseIf wks.Cells(i, 1).Value <> "" Then
heading = wks.Cells(i, 1).Value
Select Case LCase(heading)
Case "country"
wks.Cells(outRowCounter, 6).Value = wks.Cells(i, 2).Value
Case "phone"
wks.Cells(outRowCounter, 7).Value = wks.Cells(i, 2).Value
Case "email"
wks.Cells(outRowCounter, 8).Value = wks.Cells(i, 2).Value
End Select
End If
Next i
'clean up
Set wks = Nothing
End Sub
关于excel - Excel中的单列变成多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24904483/