使用vba记录一列中不同字段出现的次数,并将统计数据列出到指定工作表
以下是一个示例代码,可以通过遍历一列,记录其中不同字段出现的次数,并将统计数据列出到指定工作表中:
Sub CountOccurrences()
Dim currentRow As Long Dim lastRow As Long Dim currentField As String Dim occurrences As Long
'设置要统计的列和目标工作表 Const columnToCount = "A" Const targetSheetName = "统计结果"
'获取目标工作表 Dim targetSheet As Worksheet Set targetSheet = Worksheets(targetSheetName)
'获取要统计的最后一行 lastRow = Cells(Rows.Count, columnToCount).End(xlUp).Row
'清空目标工作表 targetSheet.Cells.ClearContents
'循环遍历列中的每一行 For currentRow = 1 To lastRow '获取当前行的值 currentField = Cells(currentRow, columnToCount).Value
'如果当前值不为空
If currentField <> "" Then
'增加当前值的出现次数
occurrences = occurrences + 1
'如果当前值已经出现过
If targetSheet.Range("A:A").Find(currentField) <> Nothing Then
'增加当前值在目标工作表中的出现次数
targetSheet.Range("B" & targetSheet.Range("A:A").Find(currentField).Row).Value = _
targetSheet.Range("B" & targetSheet.Range("A:A").Find(currentField).Row).Value + 1
Else
'否则,在目标工作表中新增一行,记录当前值和出现次数
targetSheet.Range("A" & occurrences).Value = currentField
targetSheet.Range("B" & occurrences).Value = 1
End If
End If
Next currentRow
End Sub
这个代码会在目标工作表中创建两列,第一列记录不同的字段,第二列记录对应字段出现的次数。如果需要统计的列或目标工作表名称不同,可以根据实际情况进行修改。
原文地址: https://www.cveoy.top/t/topic/xIY 著作权归作者所有。请勿转载和采集!