Vb.net 按组列出的Excel宏
表格示例Vb.net 按组列出的Excel宏,vb.net,vba,excel,Vb.net,Vba,Excel,表格示例 column1 | column2 | column3 -------------------------------------------- | | A | 1 | A | 2 | A | 3 | | | B | 4 |
column1 | column2 | column3
--------------------------------------------
| |
A | 1 |
A | 2 |
A | 3 |
| |
B | 4 |
B | 4 |
| |
C | 1 |
C | 1 |
C | 5 |
如您所见,它们被分组在第一列中,第二列是一些值。
我对VB一窍不通,一个多小时以来我自己都没能弄明白
我想做的是:
每组:
计算有多少值小于2
如果有1个或更多这样的值,则在组的空白行中设置Cuxn3,在组
组中的值/组总数中2个值以下的值。 如果没有,什么也不做 上表的输出为: 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
为什么B组没有输出?你在寻找不同的价值观吗?问题有点让人困惑。B组中的两个值都大于2,所以什么也不做。不寻找不同的值,寻找小于2的值,以及每个组的值。这似乎不起作用,所以可能我应用得不好。为什么第一个从3开始?我假设LastRow是一个常数LastRow,LastRow的变化发生在哪里?但看起来方向是对的
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