'没有考虑连续空格,再试一下
Option Explicit
Sub test()
Dim arr, i, j, a, b, t1, t2, sum, t, p
arr = Range("a3:c" & Cells(Rows.Count, "a").End(xlUp).Row - 1)
ReDim brr(1 To 10 * UBound(arr, 1), 1 To 4)
For i = 1 To UBound(arr, 1)
If Len(arr(i, 2)) Then a = a + 1: brr(a, 1) = arr(i, 1): brr(a, 2) = arr(i, 2)
If Len(arr(i, 3)) Then b = b + 1: brr(b, 3) = arr(i, 1): brr(b, 4) = arr(i, 3)
Next
For i = 1 To UBound(brr, 1)
If Len(brr(i, 2)) = 0 And Len(brr(i, 4)) = 0 Then Exit For
If Len(brr(i, 2)) = 0 Then
For j = i To UBound(brr, 1)
If Len(brr(j, 2)) Then i = j - 1: Exit For
Next
sum = 0
For j = i To 1 Step -1
sum = sum + brr(j, 4)
If Len(brr(j, 2)) > 0 Then p = j: Exit For
Next
If brr(j, 2) < sum Then
sum = sum - brr(j, 2): t = brr(j, 2)
For j = i - 1 To p Step -1: t = t - brr(j, 4): Next
b = b + 1
For j = b To i + 2 Step -1
brr(j, 3) = brr(j - 1, 3): brr(j, 4) = brr(j - 1, 4)
Next
brr(j, 3) = brr(i, 3): brr(j, 4) = sum: brr(i, 4) = t
ElseIf brr(j, 2) > sum Then
a = a + 1
For j = a To i + 2 Step -1
brr(j, 1) = brr(j - 1, 1): brr(j, 2) = brr(j - 1, 2)
Next
brr(j, 1) = vbNullString: brr(j, 2) = vbNullString
End If
Else
If brr(i, 2) < brr(i, 4) Then
b = b + 1
For j = b To i + 2 Step -1
brr(j, 3) = brr(j - 1, 3): brr(j, 4) = brr(j - 1, 4)
Next
brr(j, 3) = brr(i, 3): brr(j, 4) = brr(i, 4) - brr(i, 2): brr(i, 4) = arr(i, 2)
ElseIf brr(i, 2) > brr(i, 4) Then
a = a + 1
For j = a To i + 2 Step -1
brr(j, 1) = brr(j - 1, 1): brr(j, 2) = brr(j - 1, 2)
Next
brr(j, 1) = vbNullString: brr(j, 2) = vbNullString
End If
End If
Next
a = IIf(a > b, a, b)
With [f3]
With .Resize(2 * a, 4)
.MergeCells = False
.ClearContents
End With
.Resize(a, 4) = brr
End With
End Sub |