VBA需求:统计指定条件行数并遍历对应列唯一值
VBA统计指定列符合条件的行数并提取对应列的唯一值
需求说明
- 统计工作表
Location Groups中C列值为Yellow的总行数 - 提取C列值为
Yellow时,B列对应的所有唯一值,并通过MsgBox逐个展示
示例数据
| A | B | C |
|---|---|---|
| B1 | UG | Blue |
| B2 | DG | Blue |
| L1 | Cell 1 | Yellow |
| L2 | Cell 1 | Yellow |
| L3 | Cell 2 | Yellow |
| L4 | Cell 2 | Yellow |
| L5 | Cell 3 | Yellow |
| L6 | Cell 3 | Yellow |
| S1 | River | White |
解决方案代码
1. 统计符合条件的行数
你已写出的代码可以直接使用,补充明确的工作表引用可避免歧义:
Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Location Groups") ' 统计C列值为Yellow的总行数 Dim yellowRowCount As Long yellowRowCount = WorksheetFunction.CountIfs(ws.Range("C:C"), "Yellow") MsgBox "C列值为Yellow的总行数:" & yellowRowCount
2. 提取B列对应唯一值并遍历展示
利用VBA的Dictionary对象实现自动去重,提供两种实现方式:
后期绑定版本(无需额外引用)
Sub GetUniqueYellowBValues() Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Location Groups") Dim lastRow As Long lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row ' 获取C列最后一行,避免遍历空单元格 Dim uniqueBValues As Object Set uniqueBValues = CreateObject("Scripting.Dictionary") Dim i As Long For i = 1 To lastRow ' 判断当前行C列值是否为Yellow If ws.Cells(i, "C").Value = "Yellow" Then ' 将B列值加入字典,键的唯一性自动去重 uniqueBValues(ws.Cells(i, "B").Value) = "" End If Next i ' 遍历字典的键(即唯一值),逐个展示 Dim key As Variant For Each key In uniqueBValues.Keys MsgBox "唯一值:" & key Next key End Sub
前期绑定版本(需提前引用)
- 打开VBA编辑器,点击
工具->引用 - 勾选
Microsoft Scripting Runtime - 使用以下代码:
Sub GetUniqueYellowBValues() Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Location Groups") Dim lastRow As Long lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row Dim uniqueBValues As New Dictionary Dim i As Long For i = 1 To lastRow If ws.Cells(i, "C").Value = "Yellow" Then uniqueBValues(ws.Cells(i, "B").Value) = "" End If Next i Dim key As Variant For Each key In uniqueBValues.Keys MsgBox "唯一值:" & key Next key End Sub
代码说明
- 通过获取C列最后一行,减少无效遍历,提升运行效率
- 利用字典的键唯一性特性,自动完成去重操作,无需额外判断逻辑
- 遍历字典的键集合,即可直接获取所有唯一值并展示
内容的提问来源于stack exchange,提问作者Andrew Abbott
相关产品推荐
相关产品推荐

