|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
楼上的代码对每个小区域内数据没有随意安放,下面的代码对此问题进行了纠正。- Sub test()
- Dim d As Object
- Dim dd(1 To 4) As Object
- Dim r%, i%, c%, j%
- Dim arr, brr()
- Randomize Timer
- Set d = CreateObject("scripting.dictionary")
- For i = 1 To 4
- Set dd(i) = CreateObject("scripting.dictionary")
- Next
- With Worksheets("sheet1")
- r = .Cells(.Rows.Count, 1).End(xlUp).Row
- arr = .Range("b4:c" & r)
- For i = 1 To UBound(arr)
- If Not d.Exists(arr(i, 2)) Then
- Set d(arr(i, 2)) = CreateObject("scripting.dictionary")
- End If
- d(arr(i, 2))(arr(i, 1)) = ""
- Next
- End With
-
- For Each aa In d.Keys
- crr = d(aa).Keys
- n = Int((UBound(crr) + 1) / 4)
- For j = 1 To n
- For k = 1 To 4
- dd(k)(crr((j - 1) * 4 + k - 1)) = aa
- d(aa).Remove (crr((j - 1) * 4 + k - 1))
- Next
- Next
- Next
-
- For Each aa In d.Keys
- If d(aa).Count = 0 Then
- d.Remove (aa)
- End If
- Next
-
- For Each aa In d.Keys
- crr = d(aa).Keys
- n = Int((UBound(crr) + 1) / 2)
- For j = 1 To n
- For k = 1 To 2
- If k = 1 Then
- If dd(1).Count < dd(2).Count Then
- dd(1)(crr((j - 1) * 2 + k - 1)) = aa
- Else
- dd(2)(crr((j - 1) * 2 + k - 1)) = aa
- End If
- d(aa).Remove (crr((j - 1) * 2 + k - 1))
- Else
- If dd(3).Count < dd(4).Count Then
- dd(3)(crr((j - 1) * 2 + k - 1)) = aa
- Else
- dd(4)(crr((j - 1) * 2 + k - 1)) = aa
- End If
- d(aa).Remove (crr((j - 1) * 2 + k - 1))
- End If
- Next
- Next
- Next
- For Each aa In d.Keys
- If d(aa).Count = 0 Then
- d.Remove (aa)
- End If
- Next
- For Each aa In d.Keys
- For Each bb In d(aa).Keys
- If dd(1).Count < 8 Then
- dd(1)(bb) = aa
- ElseIf dd(2).Count < 8 Then
- dd(2)(bb) = aa
- ElseIf dd(3).Count < 8 Then
- dd(3)(bb) = aa
- Else
- dd(4)(bb) = aa
- End If
- Next
- Next
- m = 4
- With Worksheets("sheet1")
- .Columns("g:h").Clear
- For i = 1 To 4
- r = .Cells(.Rows.Count, 8).End(xlUp).Row
- If r = 1 Then r = r + 2
- .Cells(r + 1, 7).Resize(dd(i).Count, 2) = Application.Transpose(Application.Transpose(Application.Transpose(Array(dd(i).Keys, dd(i).Items))))
- Next
- r = .Cells(.Rows.Count, "g").End(xlUp).Row
- ReDim brr(1 To r - 3)
- For i = 1 To UBound(brr) Step 8
- For j = 1 To 8
- brr(i + j - 1) = (Int((i - 1) / 8) + 1) * 10 + Rnd()
- Next
- Next
- .Range("i4").Resize(UBound(brr), 1) = Application.Transpose(brr)
- .Range("g4:i" & r).Sort key1:=.Range("i4"), order1:=xlAscending, header:=xlNo
- .Columns("i:i").Clear
- End With
- End Sub
复制代码 |
|