您可以尝试使用Do...Loop
withRange.Find
方法,因为您的信息每天都会发生变化。作为一个不需要排序的示例,并且可以灵活地更改数据:
Dim bin_count As Integer 'bin count
bin_count = 1
Dim sheet2_plcmnt As Integer 'sheet 2 placeholder
sheet2_plcmnt = 1
Dim cur_row As Long 'current row
Dim nxt_row As Long 'next row
Dim loop_tst As Integer 'loop test
'---prime do...loop---
cur_row = Worksheets("Sheet1").Range("A:A").Find("Bin").Row
nxt_row = Worksheets("Sheet1").Range("A:A") _
.FindNext(Cells(cur_row, 1)).Row
loop_tst = 0
'delete previous data in Sheet2, row 1
Worksheets("Sheet2").Rows(1).Delete
'use .activate so CountIf works properly in loop below
Worksheets("Sheet1").Activate
'---run loop through all cells in column A---
'= 0 have not reached end; = 1 reached end but need to run
'one more time; = 2 exit loop
Do While loop_tst < 2
'put in values...
'bin # (contiguous, starting at 1)
Worksheets("Sheet2").Cells(1, sheet2_plcmnt).Value = _
"Bin" & bin_count
'# after bin
Worksheets("Sheet2").Cells(1, sheet2_plcmnt + 1).Value = _
Worksheets("Sheet1").Cells(cur_row + 1, 1).Value
'# of CTs after bin
If loop_tst < 1 Then
'if haven't reached end, check between cur_row and nxt_row
Worksheets("Sheet2").Cells(1, sheet2_plcmnt + 2).Value = _
WorksheetFunction.CountIf(Range(Cells(cur_row, 1), _
Cells(nxt_row, 1)), "CT")
Else
'if have reached end, check between cur_row and
'last row in column A
Worksheets("Sheet2").Cells(1, sheet2_plcmnt + 2).Value = _
WorksheetFunction.CountIf(Range(Cells(cur_row, 1), _
Range("A1").End(xlDown)), "CT")
End If
'...change counters as needed
bin_count = bin_count + 1
sheet2_plcmnt = sheet2_plcmnt + 3
cur_row = nxt_row
'set next row
nxt_row = Worksheets("Sheet1").Range("A:A") _
.FindNext(Cells(cur_row, 1)).Row
'adjust to determine loop behavior
If loop_tst = 1 Then loop_tst = 2
If cur_row > nxt_row Then loop_tst = 1
Loop
如果您使用它,请注意它会从 Sheet2 第 1 行中删除以前的数据,因此以前的计数不会留下任何残留物。
该Worksheet.Activate
方法使用一次以确保CountIf
功能正常工作。如果有人知道避免这种情况的方法,则可以修改代码以在没有任何Select
or的情况下工作Activate
。