这个宏会做除了记录之间的行之外的工作,将保留 3 行。要点是记录应该以“图像名称”开头(检查不区分大小写)。您可以稍后对其进行调整以符合要求。
Sub ReorderImageRecords()
Dim cnt As Long, curidx As Long
For i = 1 To ActiveSheet.UsedRange.Rows.Count
cnt = 0
If Left(LCase(Cells(i, 1)), 10) = "image name" Then
Cells(i + 1, 1).EntireRow.Delete
Cells(i + 1, 1).EntireRow.Delete
curidx = i
Cells(curidx + 1, 1) = "Annotation"
Cells(curidx + 1, 2) = "Comment"
Cells(curidx + 1, 3) = "Value"
Cells(curidx + 1, 4) = "Unit"
While Not IsEmpty(Cells(curidx + cnt + 2, 2))
cnt = cnt + 1
Cells(curidx + cnt + 1, 2) = Cells(curidx + cnt + 2, 3)
Cells(curidx + cnt + 2, 2).EntireRow.Delete
Wend
i = i + cnt + 1
End If
Next i
End Sub
更新
这是一个优化版本,没有curidx,并带有删除图像记录之间多余行的代码:
Sub ReorderImageRecords()
Dim cnt As Long, i As Long
For i = 1 To ActiveSheet.UsedRange.Rows.Count
cnt = 0
If i > 1 Then ' If it is not the 1st row
If Application.CountA(Cells(i - 1, 1).EntireRow) = 0 Then
Cells(i - 1, 1).EntireRow.Delete ' Delete if the whole preceding row is empty
End If
If Application.CountA(Cells(i - 1, 1).EntireRow) = 0 Then
Cells(i - 1, 1).EntireRow.Delete ' Repeat row removal
End If
End If
If Left(LCase(Cells(i, 1)), 10) = "image name" Then ' We found an image record start
Cells(i + 1, 1).EntireRow.Delete ' We delete unnecessary blank rows
Cells(i + 1, 1).EntireRow.Delete ' Repeat removal
Cells(i + 1, 1) = "Annotation" ' Insert headers
Cells(i + 1, 2) = "Comment"
Cells(i + 1, 3) = "Value"
Cells(i + 1, 4) = "Unit"
While Not IsEmpty(Cells(i + cnt + 2, 2)) ' If we are still within one and the same record
cnt = cnt + 1
Cells(i + cnt + 1, 2) = Cells(i + cnt + 2, 3) ' Copy comment
Cells(i + cnt + 2, 2).EntireRow.Delete ' Remove row with comment
Wend
i = i + cnt + 1 ' Increment row index to the current value
End If
Next i
End Sub