[英]Excel macro by group
表格示例
column1 | column2 | column3
--------------------------------------------
| |
A | 1 |
A | 2 |
A | 3 |
| |
B | 4 |
B | 4 |
| |
C | 1 |
C | 1 |
C | 5 |
如您所见,它们被分组在第一列中,第二列是一些值。 我不了解VB,而且一个多小时都无法自己弄清。
我想做的事:
对于每个组:
计算有多少个值小于2。
如果有1个或多个这样的值,请将组上方空白行中的column3设置为(numbers of values under 2 in group / total number of values in group)
组中(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 |
进行一些假设(假设您的列号与示例中的相同,并且组之间始终有空白行,下面是一个摘要片段:
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.