2009-11-22 123 views
0

我有一个表,看起来像这样:如何将多列转换为单列?

Col1  Col2  Col3  Col4 
a  b  c  d 
e  f  g  h 

我需要将其转换成这样:

Col1  New 
a  b 
a  c 
a  d 
e  f 
e  g 
e  h 

我有大量的数据和做手工,这是不可能的。有谁知道一个快速的方法来做到这一点?我希望有一个内置的方式(如paste->转置或函数?)。如果没有人可以指点我一个相关的VBA例子,因为我在VBA上生锈了。

+0

作为部分答案(因为通过VBA肯定是比你rustier,放眼串联。 – MPelletier 2009-11-22 22:27:48

+0

嗯,我认为是一样多的工作(如果不是更多)作为遍历的一切。除非是我弄错了=( – zfedoran 2009-11-22 22:32:35

回答

4

选择要变换的数据(不包括列标题)并运行以下宏。

Sub Transform() 

    Dim targetRowNumber As Long 
    targetRowNumber = Selection.Rows(Selection.Rows.Count).Row + 2 

    Dim col1 As Variant 
    Dim cell As Range 

    Dim sourceRow As Range: For Each sourceRow In Selection.Rows 

     col1 = sourceRow.Cells(1).Value 
     For Each cell In sourceRow.Cells 

      If Not cell.Column = Selection.Column Then 
       Selection.Worksheet.Cells(targetRowNumber, 1) = col1 
       Selection.Worksheet.Cells(targetRowNumber, 2) = cell.Value 
       targetRowNumber = targetRowNumber + 1 
      End If 

     Next cell 

    Next sourceRow 

End Sub 
+0

我真的希望你们不要只以我的名义写信,但是,“这完全是我所需要的”!谢谢=) – zfedoran 2009-11-22 23:01:30

+0

我做到了,但只花了几分钟,不客气。 – 2009-11-22 23:14:04