我有一张如下所示的表格:
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")