表格示例
column1 | column2 | column3
--------------------------------------------
| |
A | 1 |
A | 2 |
A | 3 |
| |
B | 4 |
B | 4 |
| |
C | 1 |
C | 1 |
C | 5 |
如您所见,它们分组在第一列,第二列是一些值。 我对VB一无所知,而且我已经能够在一个多小时内弄明白了。
我想做什么:
对于每个小组:
计算少于2的值。
如果有一个或多个此类值,请将该组上方空白行中的column3设置为(numbers of values under 2 in group / total number of values in group)
如果没有,则什么都不做。
上表的输出为:
column1 | column2 | column3
--------------------------------------------
| | 1/3
A | 1 |
A | 2 |
A | 3 |
| |
B | 4 |
B | 4 |
| | 2/3
C | 1 |
C | 1 |
C | 5 |
答案 0 :(得分:1)
做出一些假设(您的列号与示例中的列号相同,并且组之间总是有一个空白行,这是一个开头的代码段:
Sub Test2()
Dim LastRow As Integer, First As Integer, Last As Integer
LastRow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious, After:=[A1]).Row + 1
First = 3
For i = 3 To LastRow
If Cells(i, 1).Value = "" Then
Last = i - 1
Cells(First - 1, 3).Value = Summ(First, Last)
First = i + 1
End If
Next i
End Sub
Private Function Summ(First As Integer, Last As Integer)
Dim Count As Integer, Total As Integer
For t = First To Last
Total = Total + 1
If Cells(t, 2).Value < 2 Then Count = Count + 1
Next t
Summ = Count / Total
End Function
答案 1 :(得分:1)
Sub calculatebygroups()
last_row = Cells.SpecialCells(xlCellTypeLastCell).Row
group_counter = 0
value_counter = 0
row_to_write = 0
For n = 1 To last_row + 1
If Range("A" & n).Value = "" Then
If row_to_write <> 0 And value_counter <> 0 Then
Range("C" & row_to_write).Value = "'" & value_counter & "/" & group_counter
End If
row_to_write = n
group_counter = 0
value_counter = 0
Else
group_counter = group_counter + 1
If Range("B" & n).Value < 2 Then
value_counter = value_counter + 1
End If
End If
Next n
End Sub