修改了一下再试试
Option Explicit
Sub test()
Dim i, j, k, kk, arr, n, t, dt, tt
dt = Timer
With Sheets("数据库原表")
arr = .Range("a2:e" & .Cells(Rows.Count, "c").End(xlUp).Row + 1)
End With
ReDim brr(1 To UBound(arr, 1), 1 To UBound(arr, 2))
For i = 1 To UBound(arr, 1) - 1
For j = i To UBound(arr, 1) - 1
If arr(j, 1) <> arr(j + 1, 1) Or Len(arr(j + 1, 3)) = 0 Then
tt = Replace(arr(i, 2), Space(1), vbNullString)
If j > i And InStr(tt, "户主") = 0 Then '户主位置判断,同户号单人不做判断
For k = i To j
tt = Replace(arr(k, 2), Space(1), vbNullString)
If InStr(tt, "户主") Then '找到户主
For kk = 1 To UBound(arr, 2) '户主移到同户号的第一行
t = arr(i, kk): arr(i, kk) = arr(k, kk): arr(k, kk) = t
Next
Exit For '找到户主移位后直接退出,因为不可能有2个户主
End If
Next
End If
For k = i To j
n = n + 1
If k = i Then '处理户主一行
brr(n, 1) = arr(k, 5): brr(n, 2) = arr(k, 3): brr(n, 3) = arr(k, 4)
If j > i Then '同户号多人
brr(n, 4) = arr(k + 1, 3): brr(n, 5) = arr(k + 1, 4)
k = k + 1 '处理户主一行时处理了2个人的数据,跳过下一行
Else '同户号单人
Exit For '不作其他人处理,直接退出
End If
Else
brr(n, 4) = arr(k, 3): brr(n, 5) = arr(k, 4) '户主外多人
End If
Next
i = j: Exit For '当前同户号的所有人处理完毕继续下一户号
End If
Next j, i
Debug.Print Timer - dt
With Sheets("转换后生成的表").[a3]
.Resize(Rows.Count - 2, UBound(arr, 2)).ClearContents
.Resize(n, UBound(brr, 2)) = brr
End With
Debug.Print Timer - dt
End Sub |