Excel VBA
자동 필터 후 자동필터 목록에 있는 데이터 개수 구하기
VBA는 취미로
2024. 7. 11. 22:10
Sub CountUniqueFilteredValues()
Dim rng As Range
Dim dict As Object
Dim cell As Range
Dim uniqueCount As Long
Dim ws As Worksheet
' 현재 활성 워크시트 설정
Set ws = ActiveSheet
' 범위 설정
Set rng = ws.Range("A2").CurrentRegion
' 자동 필터 모드 확인
If Not ws.AutoFilterMode Then
MsgBox "자동 필터가 적용되어 있지 않습니다. 먼저 필터를 적용해 주세요.", vbInformation
Exit Sub
Else
End If
' 필터링 상태 확인
If Not ws.FilterMode Then
MsgBox "필터가 적용되어 있지 않습니다. 필터를 적용한 후 다시 시도해 주세요.", vbInformation
Exit Sub
Else
End If
' Dictionary 개체 생성
Set dict = CreateObject("Scripting.Dictionary")
' B열의 필터된 셀들을 순회하며 고유 값 카운트
For Each cell In rng.Columns(2).SpecialCells(xlCellTypeVisible)
If Not IsEmpty(cell) Then
dict(cell.Value) = 1
End If
Next cell
' 고유 값 개수 계산
uniqueCount = dict.Count
' 결과 출력
MsgBox "B열의 고유 값 개수: " & uniqueCount, vbInformation
' 자동 필터 해제
ws.AutoFilterMode = False
' 개체 해제
Set dict = Nothing
End Sub
* 수식으로도 가능하지만 매크로 초보이므로 간단하게 만들어 본 코드입니다.