Excel で 2 行の複数の列をそれぞれ別の行に配置する VBA

Excel で 2 行の複数の列をそれぞれ別の行に配置する VBA

次のようなシートがあります:

   A   |   B   |   C   |   D   |   E   |
----------------------------------------
     62| Value1| Value2|       |       |
    345| Value3| Value4| Value5| Value6|
     17| Value7| Value0|       |       |
    111| Value8| Value9| ValueA|ValueC |

これを次のように変換したいと思います (A は標準、次の 2 つのセルは B と C、D と E など)。

   A   |   B   | C    |
-----------------------
     62| Value1|Value2|
    345| Value3|Value4|
    345| Value5|Value6|
     17| Value7|Value0|
    111| Value8|Value9|
    111| ValueA|ValueC|

現在、1 行のみを変換する以下のマクロを使用していますが、2 つのセル値も必要です。

Sub Transform()

Dim rowStr As String
Dim rowIndex As Integer

rowIndex = 1

For Each Cell In Sheet1.Range("A1:E5")
    If Cell.Column = 1 Then
        rowStr = Cell.Value
    ElseIf Not IsEmpty(Cell.Value) Then
        Sheet2.Cells(rowIndex, 1) = rowStr
        Sheet2.Cells(rowIndex, 2) = Cell.Value
        rowIndex = rowIndex + 1
    End If
Next Cell

End Sub

答え1

私はこれを使います。

Sub Transform_2()

Dim c As Range
Dim rngFirstCol As Range
Dim rowIndex As Long
Dim j As Long

rowIndex = 1
Set rngFirstCol = Sheet1.Range(Sheet1.Cells(1, 1), Sheet1.Cells(1, 1).End(xlDown))
For Each c In rngFirstCol
  For j = 0 To rngFirstCol.CurrentRegion.Columns.Count - 2 Step 2
    If c.Offset(, j + 1).Value <> "" Or c.Offset(, j + 2).Value <> "" Then
      Sheet2.Cells(rowIndex, 1).Value = c.Value
      Sheet2.Cells(rowIndex, 2).Resize(1, 2).Value = c.Offset(, j + 1).Resize(1, 2).Value
      rowIndex = rowIndex + 1
    End If
  Next
Next

End Sub

データテーブルの行数を自動的に決定します。必要に応じて、変更して自分で設定することもできます。

Sheet1.Range(Sheet1.Cells(1, 1), Sheet1.Cells(1, 1).End(xlDown))

列参照のように

Sheet1.Range("A1:A6")

関連情報