Excel에서 두 행이 있는 여러 열을 자체 행에 배치하는 VBA

Excel에서 두 행이 있는 여러 열을 자체 행에 배치하는 VBA

다음과 같은 시트가 있습니다.

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

이를 다음과 같이 변환하고 싶습니다(A는 표준이고 다음 두 셀 - 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|

현재 하나의 행만 변환하여 아래 매크로를 사용하고 있지만 두 개의 셀 값을 사용하고 싶습니다.

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")

관련 정보