Excel - 转置列对

Excel - transpose pairs of columns

我正在尝试将成对的列转置为重复的行(如果这是该术语的正确应用)。具体来说,我需要从这个开始:

Thing1     6    0.29    5   0.23    7   0.19    8   0.11

对此:

Thing1     6    0.29
Thing1     5    0.23
Thing1     7    0.19
Thing1     8    0.11

此操作将发生在至少 7 对列中,数百个 "things." 我无法弄清楚的部分是如何 group/lock 将这些对视为一个单元。

在某些方面,我试图做与通常所做的相反的事情。一个例子在这里:Transpose and group data 但它不太合适,即使我试图向后看。

编辑:另一个类似的例子,但我需要做几乎相反的事情:How to transpose one or more column pairs to the matching record in Excel?

我的VBA功夫很弱,但是你们的集体智慧,我愿意一试。

欢迎提出想法,无论如何,感谢您的阅读。

这是一个VBA解决方案。

要执行此操作,请按 Alt+F11 打开 VBA 编辑器。

右击左侧select"Insert Module"

将代码粘贴到右侧。

您可能想要更改输出 sheet 名称,如我在代码中所示。

我是用Sheet2放置转置后的数据,大家可以随意使用

完成此操作后,您可以关闭编辑器并 select 包含您的 non-transposed 数据的 sheet。

运行 宏,方法是按 Alt+F8,单击宏,然后按 Run

Sheet2 应该包含您要查找的结果。

Sub ForJeremy() 'You can call this whatever you want
Dim EndCol, OutSheet, OutRow, c, x
Application.ScreenUpdating = False
EndCol = ActiveSheet.UsedRange.columns.Count

'What sheet do I put these values on?
Set OutSheet = Sheets("Sheet2") 'Put the name in the quotes

OutSheet.Cells.Delete xlShiftUp 'This clears the output sheet.
OutRow = 1
For Each c In Intersect(ActiveSheet.UsedRange, ActiveSheet.Range("A:A"))
    For x = 2 To EndCol Step 2
        OutSheet.Cells(OutRow, 1) = c.Value
        OutSheet.Cells(OutRow, 2) = Cells(c.Row, x)
        OutSheet.Cells(OutRow, 3) = Cells(c.Row, x + 1)
        OutRow = OutRow + 1
    Next x
Next c
OutSheet.Select
Application.ScreenUpdating = True
End Sub

输入:

输出:

编辑:如果你想在开头添加一个额外的列,它也只会显示在旁边,你可以像这样更改代码:

For Each c In Intersect(ActiveSheet.UsedRange, ActiveSheet.Range("A:A"))
    For x = 3 To EndCol Step 2 'Changed 2 to 3
        OutSheet.Cells(OutRow, 1) = c.Value
        OutSheet.Cells(OutRow, 2) = Cells(c.Row, 2) 'Added this line
        OutSheet.Cells(OutRow, 3) = Cells(c.Row, x) 'Changed to Col 3
        OutSheet.Cells(OutRow, 4) = Cells(c.Row, x + 1) 'Changed to Col 4
        OutRow = OutRow + 1
    Next x
Next c

为了更好地解释这个循环,

它从上到下遍历第 A 列中的每个单元格。

内部循环一次移动 2 列。

所以我们从第 B 列开始,接下来是 D,接下来是 F .. 等等。

所以一旦我们有了那个值,我们也获取它右边的值。

这就是 Cells(c.Row, x)Cells(c.Row, x + 1) 的作用。

OutSheet.Cells(OutRow, 1) = c.Value 说 - 只需让第一列与第一列匹配即可。

当我们添加第二个时,OutSheet.Cells(OutRow, 2) = Cells(c.Row, 2) 'Added this line我们说的是,也匹配第二列。

希望我解释得不错。

这里是Excel公式的解法,以防万一。如果源数据从 A1 开始,则第一个目标单元格中​​的公式将为 =$A,右侧的 2 个公式将为

= OFFSET( A, 0, ROW( A1 ) * 2 - 1 )

= OFFSET( A, 0, ROW( A1 ) * 2 )

复制 3 个公式单元格并粘贴到它们下方的范围内

更新

VBA 版本(将 r 设置为源区域并将 c3 替换为目标区域中的第一个单元格)

Set r = [a1:i1]
set d = [c3].Resize(r.Count \ 2, 3)
d.Formula = "=index(" & r.Address & ",if(column(a1)=1,1,row(a1)*2-2+column(a1)))"