Excel转置公式

我一直在围绕它的一段时间,只是不知道如何解决这个问题。 我的表由我想从行转换到列的数据组组成。 每一行在第一列中都有一个索引号,一个组中的所有行都有相同的索引。

1 a
1 b
1 c
1 d
1 e
1 f
1 g
1 h
2 as
2 bs
2 cs
5 ma
5 mb
5 mc
5 md

我希望我的最终结果是:

1 abcdefgh
2 as bs cs
5 ma mb mc md

是否有可能与公式做到这一点,或者我必须在VBA中做到这一点?

是的,可能的。 您将需要以下function:

  1. 如果
  2. 比赛
  3. ISNA
  4. 指数

假设您具有表A中A和B列中的数据:

在这里输入图像说明

C1:

在单元格C1中放置值“1”

C2:

= C1 + 1

尽可能多地拖下去

D1

 =MATCH(C1,A:A, 0) 

向下拖动与单元格C2一样多

E1

 =MATCH(C1,A:A, 1) 

向下拖动与单元格C2一样多

第2页: 在这里输入图像说明

现在将下面的公式放在sheet2的单元格A1中:

 =IF(ISNA(Sheet1!$D1), "", IF(Sheet1!$D1="", "", IF(COLUMN()-1+Sheet1!$D1 <=Sheet1!$E1, INDEX(Sheet1!$B:$B, COLUMN()-1+Sheet1!$D1), ""))) 

将其拖动/复制到所需的单元格数量:

在这里输入图像说明

结果:

在这里输入图像说明

另外我在我的博客上有一篇关于INDEX函数的文章。 这可能有助于Excel INDEX函数 。

您也可以在这里下载完整的文件。

你也可以使用macros来做到这一点。 这是一种方法。

要input这个macros(Sub), alt-F11打开Visual Basic编辑器。 确保您的项目在“项目浏览器”窗口中突出显示。 然后,从顶部菜单中select插入/模块,然后将下面的代码粘贴到打开的窗口中。

要使用这个macros(Sub), alt-F8打开macros对话框。 按名称selectmacros,并运行

 Option Explicit Sub ReArrange() Dim vSrc As Variant, rSrc As Range Dim vRes As Variant, rRes As Range Dim I As Long, J As Long, K As Long Dim lColsCount As Long Dim Col As Collection 'Upper left cell of results Set rRes = Range("D1") 'Assume Data in A1:Bn with no labels Set rSrc = Range("a1", Cells(Rows.Count, "A").End(xlUp)).Resize(columnsize:=2) 'Ensure Data sorted by index number rSrc.Sort key1:=rSrc.Columns(1), order1:=xlAscending, key2:=rSrc.Columns(2), order2:=xlAscending, MatchCase:=False, _ Header:=xlNo 'Read Source data into array for faster processing ' compared with going back and forth to worksheet vSrc = rSrc 'Compute Number of rows = unique count of index numbers 'Collection object can only have one entry per key ' otherwise it produces an error, which we skip Set Col = New Collection On Error Resume Next For I = 1 To UBound(vSrc) Col.Add Item:=vSrc(I, 1), Key:=CStr(vSrc(I, 1)) Next I On Error GoTo 0 'Compute Maximum Number of columns in results ' Since there is one entry per Index entry, maximum number of ' columns will be equal to the Index that has the most lines ' So we iterate through each Index and check that. For I = 1 To Col.Count J = WorksheetFunction.CountIf(rSrc.Columns(1), Col(I)) lColsCount = IIf(J > lColsCount, J, lColsCount) Next I 'Set up Results array ' Need to add one to the columns to account for the column with the Index labels ReDim vRes(1 To Col.Count, 1 To lColsCount + 1) 'Now populate the results array K = 1 For I = 1 To Col.Count vRes(I, 1) = vSrc(K, 1) J = 2 Do vRes(I, J) = vSrc(K, 2) J = J + 1: K = K + 1 If K > UBound(vSrc) Then Exit Do Loop Until vSrc(K, 1) <> vRes(I, 1) Next I 'Set the results range to be the same size as our array Set rRes = rRes.Resize(rowsize:=UBound(vRes, 1), columnsize:=UBound(vRes, 2)) 'Clear the results range and then copy the results array to it rRes.EntireColumn.Clear rRes = vRes 'Format the width. Could also format other parameters rRes.EntireColumn.ColumnWidth = 10 End Sub