答案1
可以通过 VBA 获得所需的结果。分隔符单元格已修改:在 OP 的图像上,它们是彩色的,在我的图像上,它们包含字符-
。这使得获取具有值/字符的最后一个单元格变得更容易。
选择将显示结果的(第一个)单元格。按Alt+F11打开 VBA 编辑器。输入以下代码:
Sub Counting()
Dim i, lRow, actRow, actCol, cnt As Integer
actCol = ActiveCell.Cells.Column 'Get the active cell column
lRow = Cells(Rows.Count, actCol).End(xlUp).Row 'Get the last cell of the active column that has a non blank value
actRow = lRow + 1 'Set the active cell row
i = 1 'Set the while counter
cnt = 1 'Set the group counter
While i <= lRow - 1 'Loop from first cell to last cell with non blank value
If Cells(i, actCol) = Cells(i + 1, actCol) Then
cnt = cnt + 1
Else
Cells(actRow, actCol) = cnt
actRow = actRow + 1 'This allows to set the next row that will hold the group count
cnt = 1 'Reset the counter
End If
i = i + 1
Wend
End Sub
将光标置于代码内,按下F5或运行按钮。您需要手动为每一列运行代码。您可以添加一个循环来自动遍历各列。
答案2
我试了一下,能够让它自动运行所有列。我通过嵌套 while 语句来实现。我不擅长 VBA,所以任何关于如何做得更好的想法都会很高兴收到。
Private Sub Counting()
Dim i, x, lRow, actRow, actCol, lCol, cnt As Integer
lCol = Cells(32, Columns.Count).End(xlToLeft).Column 'This line gets the last column
actCol = 1 'Get the active cell column
lRow = Range("A1:A100").Find(What:="End").Row 'Get the last cell of the active column that has a non blank value
actRow = lRow + 1 'Set the active cell row
x = 1
While x <= lCol
i = 1 'Set the while counter
cnt = 1 'Set the group counter
While i <= lRow - 1 'Loop from first cell to last cell with non blank value
If Cells(i, actCol) = Cells(i + 1, actCol) Then
cnt = cnt + 1
Else
Cells(actRow, actCol) = cnt
actRow = actRow + 1 'This allows to set the next row that will hold the group count
cnt = 1 'Reset the counter
End If
i = i + 1
Wend
actRow = lRow + 1
actCol = actCol + 1
x = x + 1
Wend
End Sub