将多行合并为一行 - Excel

时间:2016-11-15 21:20:52

标签: excel excel-vba vba

我需要帮助找到一种方法,在excel中将多行组合成一行。

例如,我在行1-4和5-8中有8列(A-H)数据(表1)。我需要一种方法将行2 - 4的所有列移动到第1行的第I列 - 第1行的AF和第4行的所有列 - 第5行的第I列 - AF(表2)。产生的空行也不是必需的。实际上,我需要多次应用此方法。有任何想法吗?

stg = Student & "2016"

1 个答案:

答案 0 :(得分:0)

我注意开发VBA代码,我不知道你在Excel中的水平。我也注意使代码尽可能简单。 在此代码中(如下): Sheets1是显示和读取数据的工作表。 Sheet2是写入数据的工作表。 RowsColsTransformer()是要运行的过程。

' VBA:

Sub RowsColsTransformer()
Dim CurrentLine As Integer
Dim CurrentLine2 As Integer
Dim CurrentCols2 As Integer
Dim Max As Integer

CurrentLine2 = 2
CurrentCols2 = 1
Max = 10 ' -- Number of lines in the sheet where data will be read.
For CurrentLine = 2 To Max
    Sheets(2).Cells(CurrentLine2, CurrentCols2) = Sheets(1).Cells(CurrentLine, 1)
    CurrentCols2 = CurrentCols2 + 1
    Sheets(2).Cells(CurrentLine2, CurrentCols2) = Sheets(1).Cells(CurrentLine, 2)
    CurrentCols2 = CurrentCols2 + 1
    Sheets(2).Cells(CurrentLine2, CurrentCols2) = Sheets(1).Cells(CurrentLine, 3)
    CurrentCols2 = CurrentCols2 + 1
    Sheets(2).Cells(CurrentLine2, CurrentCols2) = Sheets(1).Cells(CurrentLine, 4)
    CurrentCols2 = CurrentCols2 + 1
    Sheets(2).Cells(CurrentLine2, CurrentCols2) = Sheets(1).Cells(CurrentLine, 5)
    CurrentCols2 = CurrentCols2 + 1
    Sheets(2).Cells(CurrentLine2, CurrentCols2) = Sheets(1).Cells(CurrentLine, 6)
    CurrentCols2 = CurrentCols2 + 1
    Sheets(2).Cells(CurrentLine2, CurrentCols2) = Sheets(1).Cells(CurrentLine, 7)
    CurrentCols2 = CurrentCols2 + 1
    Sheets(2).Cells(CurrentLine2, CurrentCols2) = Sheets(1).Cells(CurrentLine, 8)
    CurrentCols2 = CurrentCols2 + 1
    '-- Reintialize Line and Column
    If CurrentLine Mod 4 = 1 And CurrentLine > 1 Then
        CurrentLine2 = CurrentLine2 + 1
        CurrentCols2 = 1
    End If
Next CurrentLine
End Sub

Holp这可以提供帮助。