|
Sub ProcessData()
Dim ws As Worksheet
Dim lastRow As Long
Dim currentRow As Long
Dim nonEmptyCount As Long
Dim i As Long, j As Long
Dim insertRows As Long
Dim cell As Range
Set ws = ThisWorkbook.Sheets("123") ' 修改为你的工作表名称
lastRow = ws.Cells(ws.Rows.Count, "E").End(xlUp).Row ' 找到最后一行
For currentRow = 2 To lastRow ' 从第二行开始
' 统计当前行E到AA的非空单元格数量
nonEmptyCount = Application.WorksheetFunction.CountA(ws.Range(ws.Cells(currentRow, "E"), ws.Cells(currentRow, "AA")))
If nonEmptyCount > 0 Then
' 计算需要插入的行数
insertRows = nonEmptyCount - 1
' 在当前行下方插入行
If insertRows > 0 Then
ws.Rows(currentRow + 1 & ":" & currentRow + insertRows).Insert Shift:=xlDown
End If
' 填充A列和C列
ws.Range(ws.Cells(currentRow, "A"), ws.Cells(currentRow + insertRows, "A")).Value = ws.Cells(currentRow, "A").Value
ws.Range(ws.Cells(currentRow, "C"), ws.Cells(currentRow + insertRows, "C")).Value = ws.Cells(currentRow, "C").Value
' 数据转置到D列
j = 0
For Each cell In ws.Range(ws.Cells(currentRow, "E"), ws.Cells(currentRow, "AA"))
If Not IsEmpty(cell.Value) Then
ws.Cells(currentRow + j, "D").Value = cell.Value
j = j + 1
End If
Next cell
' 数据转置到B列
j = 0
For i = 1 To 23 ' E1到AA1共23列
If Not IsEmpty(ws.Cells(1, i + 4).Value) And Not IsEmpty(ws.Cells(currentRow, i + 4).Value) Then
ws.Cells(currentRow + j, "B").Value = ws.Cells(1, i + 4).Value
j = j + 1
End If
Next i
' 更新lastRow
lastRow = ws.Cells(ws.Rows.Count, "E").End(xlUp).Row
End If
' 跳过插入的行
currentRow = currentRow + insertRows
Next currentRow
End Sub
[url=]新建 XLSX 工作表 - 副本.rar[/url]
执行上述代码后,AA列有空单元格的,都不能执行插入行,大神们看看代码是哪里出了问题,帮忙修改一下
|
|