如何将每第n列转换为行?

时间:2014-02-04 04:37:08

标签: excel-vba excel-2007 vba excel

我正在看这个宏:

Sub Spl_Transpose() 
Dim i, LastRow 
LastRow = Range("A" & Rows.Count).End(xlUp).Row 
For i = LastRow To 1 Step -2 
Cells(i, "A").Offset(-1, 1).Value = Cells(i, "A").Value 
Cells(i, "A").EntireRow.Delete 
Next 
End Sub 

上面的宏将每隔一列变成一行。

我创建了一个长3-field CSV in Excel。我希望每个1st column进入A,每个2nd column进入B,每3rd column进入C。任何人都可以告诉我如何转换上面的宏并实现它吗?

示例输入:

     A        B       C          D        E           F          G         H           I          J         K        L          
1    fruit    bowl    kitchen    bread    breadbox    kitchen    cereal    cupboard    kitchen    stereo    floor    living room

示例输出:

A       B      C
fruit   bowl   kitchen
bread   breadbox   kitchen
cereal   cupboard   kitchen
stereo   floor   living room

我想知道需要改变什么才能将其增加到A B C D场景。

1 个答案:

答案 0 :(得分:1)

要做你想问的事,你需要迭代四件事:

  1. 原始数据集中的行
  2. 每行中的单元格(列)
  3. 目标工作表行(当您在那里粘贴数据时)
  4. 目标工作表列(当您在那里粘贴数据时)
  5. 因此,我们创建了两个循环,一个循环遍历原始数据集行,另一个循环遍历该行中的单元格。

    然后我们使用两个计数器来跟踪目标表的行,这样一旦填充了三个单元格,我们就可以移动到下一行。

    Option Explicit
    
    Sub test()
    'This example places the data (output) on Sheet2.
    Dim lastRow As Long
    Dim lastCol As Long
    Dim i1 As Long
    Dim i2 As Long
    Dim i3 As Long
    Dim i4 As Long
    Dim lFields As Long
    Dim ws As Worksheet
    Dim sht As Worksheet
    Dim wb As Workbook
    
    lField = Application.InputBox("Please enter the number of fields.", _
             "Number of Fields", Type:=1) 
    
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")   'Dataset sheet.
    Set sht = wb.Sheets("Sheet2")  'Destination sheet.
    lastRow = ws.Range("A:A").Find("*", searchdirection:=xlPrevious).Row
    i3 = 1
    i4 = 1
    
    For i1 = lastRow To 1 Step -1 'Loop through rows.
        lastCol = ws.Rows("" & i1 & ":" & i1 & "").Find("*", searchdirection:=xlPrevious).Column
        For i2 = 1 To lastCol 'Loop through cells in row.
            sht.Cells(i3, i4) = ws.Cells(i1, i2).Value
            If sht.Cells(i3, lField) <> vbNullString Then i3 = i3 + 1 'Stay on row until third _
                                                                 'column (field) is full. _ 
                                                                 'To add a column, change _
                                                                 '".Cells(i3,3)" to ".Cells(i3,4)"
            i4 = i4 + 1
            If i4 = lField + 1 Then i4 = 1 '<~~ This is what controls how many columns are _
                                  '    in the output. To add a column (field), change _ 
                                  '    "If i4 = 4" to "If i4 = 5".
        Next i2
    Next i1
    
    End Sub
    

    此示例从数据集的底部循环到顶部,但可以通过更改第一个循环从

    轻松修改为从上到下
    For i1 = lastRow To 1 Step -1
    

    For i1 = 1 To lastRow