Created
July 20, 2021 22:09
-
-
Save LaughDonor/22a86f7f609eb317d6ea77f5943e600a to your computer and use it in GitHub Desktop.
Excel VBA Function to count all distinct values across multiple tables (same column name)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Option Explicit | |
Function CountUnique(TableNames As Range, ColumnName As String) As Long | |
Dim TableName | |
Dim TempRange As Range | |
Dim Rng As Range | |
Dim List As Object | |
' Iterate through every range and push cell values to dictionary keys, and count the keys | |
With CreateObject("Scripting.Dictionary") | |
For Each TableName In TableNames.Cells | |
Set TempRange = GetTableRange(TableName.Value, ColumnName) | |
If Not TempRange Is Nothing Then | |
For Each Rng In TempRange | |
If Rng.Value <> "" And Not .Exists(Rng.Value) Then .Add Rng.Value, Nothing | |
Next | |
End If | |
Next | |
CountUnique = .Count | |
End With | |
End Function | |
' Search each sheet for table with given name and fetch the range with given column name | |
Private Function GetTableRange(Name As String, ColumnName As String) As Range | |
Dim Sheet As Worksheet | |
For Each Sheet In ThisWorkbook.Worksheets | |
On Error Resume Next | |
Set GetTableRange = Sheet.ListObjects(Name).ListColumns(ColumnName).DataBodyRange | |
If Not GetTableRange Is Nothing Then Exit Function | |
Next | |
GetTableRange = Nothing | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment