VBA将行转换为列

时间:2014-11-25 14:45:19

标签: excel vba excel-vba

我在Excel中有一个看起来像这样的工作表

name          variant1          value1          variant2          value2
-----         --------          ------          --------          ------    
name1         variantA1         valueA1         variantB1         valueB1
name2         variantC2         valueC2         variantD2         valueD2

我想将其转换为这样的结构:

name          variant          value
----          --------         ------
name1         
              variantA1        valueA1
              variantB1        valueB2
name2         
              variantC2        valueC2
              variantD2        valueD2

我会经常使用这个宏,可能会发生每个名称将有10个不同的变体,我不知道工作表中会有多少行。

我写了VBA宏,但我不确定它为什么不起作用:

Sub import_format()

Dim ws As Worksheet
Dim LastRow As Long, i As Long
Dim NumberOfVariants As Long
Dim j As Long
Dim ColumnIndex As Long


Set ws = Sheets("Sheet1") '~~> Name of the sheet which has the list
LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
NumberOfVariants = 2
ColumnIndex = 2 '<~~ index of the first variant


For i = 2 To LastRow '<~~ Set 2 if row 1 has headers
    i = i + 1
    ws.Rows(i & ":" & i + NumberOfVariants).Insert shift:=xlDown
    i = i - 1
    For j = 0 To (NumberOfVariants * 2) - 1
        ws.Range(Cells(ColumnIndex + (j * 2), i), Cells(ColumnIndex + (j * 2) + 1, i)).Select
        Selection.Cut
        ws.Range(Cells(ColumnIndex + (j * 2), i + j + 1), Cells(ColumnIndex + (j * 2) + 1, i + j + 1)).Paste
    Next j
Next i

End Sub

我尝试这样做的方法是插入rows =变体数量并剪切和粘贴正确的值。

我会很感激所有的提示! ; - )

1 个答案:

答案 0 :(得分:0)

试试这个:)

Option Explicit
Sub import_format()

Dim ws As Worksheet
Dim i, j, LastRow, ColumnIndex, NumberOfVariants As Integer


Set ws = Sheets("Sheet1") '~~> Name of the sheet which has the list
LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
NumberOfVariants = 4
ColumnIndex = 2 '<~~ index of the first variant


For i = 2 To LastRow + (LastRow - 2) * (NumberOfVariants - 1) Step NumberOfVariants '<~~ Set 2 if row 1 has headers; Actual last row = current last row + lines which will be inserted
    ws.Rows(i + 1 & ":" & i + NumberOfVariants - 1).Insert shift:=xlDown 'Insert rows based on number of variants
    For j = 2 To (NumberOfVariants - 1) * 2 Step 2 'Walking through the variants, starting in column 2, variant + value are 2 columns, therefore using step 2
        ws.Range(Cells(i, ColumnIndex + j), Cells(i, ColumnIndex + j + 1)).Cut _
        Destination:=ws.Range(Cells(i + j / 2, ColumnIndex), Cells(i + j / 2, ColumnIndex + 1))
    Next j
Next i

End Sub