Excel 2010:使用VBA将单元格从垂直数据移动到水平

时间:2015-02-11 15:39:33

标签: vba excel-vba excel-2010 excel

Excel 2010

我想将以下数据从其垂直状态移动到水平数据。我想在VBA中找到解决方案。 (我已经有了一个公式)。

订单=(A10)结果=(B10)超过1000行

| Order1         | result                                                                       
| line1          | result 1
| line2          | result 1
| line3          | result 1
| line4          | result 1
| line5          | result 1
| line6          | result 1
| line7          | result 1
| line8          | result 1
|      br        |                                                                           
| Order2         | result                                                                   
| line1          | result 1
| line2          | result 1
| line3          | result 1
| line4          | result 1
| line5          | result 1
| line6          | result 1
| line7          | result 1
| line8          | result 1

我希望它解决为:

Order 1  |  result1  |  result2  |  result3  |  result4  |  result5  |  result6  |  result7  |  result8  |  
Order 2  |  result1  |  result2  |  result3  |  result4  |  result5  |  result6  |  result7  |  result8  |  

提前致谢

修改
我目前的公式是这样的: (C10)=IF(A3="Order1 ",1,0)(结果:1)
(D10)=IF($C3=1,B3,0)(结果:第1行的结果)
(E10)=IF($C3=1,B10,0)(结果:第2行的结果)
等等。

然后我复制并自动填充整个数据表,并将其全部填入。 我用这种方式构建新表。

当我进行宏录制时,它不会记录我在单元格中的实际公式。

1 个答案:

答案 0 :(得分:2)

如果我们开始:

enter image description here

Sheet1 中的订单之间有空白,然后是这个宏:

Sub reorg()
    Dim s1 As Worksheet, s2 As Worksheet, N As Long, i As Long, j As Long, k As Long
    Dim v As Variant
    Set s1 = Sheets("Sheet1")
    Set s2 = Sheets("Sheet2")
    N = s1.Cells(Rows.Count, "A").End(xlUp).Row
    j = 1
    k = 1

    For i = 1 To N
        v = s1.Cells(i, 1).Value
        If v = "" Then
            j = j + 1
            k = 1
        Else
            s2.Cells(j, k) = v
            k = k + 1
        End If
    Next i
End Sub

将在 Sheet2

中生成此内容

enter image description here

修改#1:

要将 A10 用作开头和目的地,请使用:

Sub reorg()
    Dim s1 As Worksheet, s2 As Worksheet, N As Long, i As Long, j As Long, k As Long
    Dim v As Variant
    Set s1 = Sheets("Sheet1")
    Set s2 = Sheets("Sheet2")
    N = s1.Cells(Rows.Count, "A").End(xlUp).Row
    j = 10
    k = 1

    For i = 10 To N
        v = s1.Cells(i, 1).Value
        If v = "" Then
            j = j + 1
            k = 1
        Else
            s2.Cells(j, k) = v
            k = k + 1
        End If
    Next i
End Sub