VBAでシート上の項目のカウントを行いときは
Dictionaryオブジェクトを使用すると
簡単に項目のカウントを行うことができます。
Dictionaryオブジェクトを使用するために
Microsoft Scripting Runtimeに事前に参照設定を行う必要があります。

VBAで参照設定を行う
VBAに標準で含まれていない機能があるときは
外部のライブラリを参照して、外部ライブラリ内の機能を利用します。
この外部ライブラリの機能を利用する設定を、参照設定と言います。
シートのA列に4種類の食べ物が入力されています。
・りんご
・レタス
・牛肉
・水
こちらのデータのカウントを行ってみます。
シート上の項目のカウントを行うコードは以下になります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
Option Explicit Sub countItems(sht As Worksheet, col As Long) '################################################################################### 'シート上の項目のカウントを行い、表示する 'Dictionaryを使用するので、Microsoft Scripting Runtimeの参照設定が必要 '----------------------------------------------------------------------------------- '引数 :sht データのカウントを行いたいシート ' :col データのカウントを行いたい列番号 '################################################################################### Dim lastRow As Long lastRow = getMaxRow(sht, col) Dim dic As Dictionary Set dic = New Dictionary Dim i As Long Dim v As String For i = 1 To lastRow v = sht.Cells(i, 1).Value '必ずCells.Valueを指定する If dic.Exists(v) Then dic(v) = dic(v) + 1 Else dic.Add v, 1 End If Next i For i = 0 To dic.Count - 1 MsgBox dic.Keys(i) & "は" & dic.Items(i) & "個" Next i Set dic = Nothing End Sub Function getMaxRow(sht As Worksheet, targetCol As Long) As Long getMaxRow = sht.Cells(sht.Rows.Count, targetCol).End(xlUp).Row End Function Sub test_countItems() Dim sht As Worksheet Set sht = ThisWorkbook.Worksheets("Sheet1") Call countItems(sht, 1) Set sht = Nothing End Sub |
データの最終行を取得するために、getMaxRow Functionを使用しています。
getMaxRowについては以下の記事をご覧ください。

【VBA】最終行・最終列を取得する
for文などで1行目から最終行、または1列目から最終列まで
連続して処理を行いたいときがあります。
この記事では最終行と最終列を取得するVBAのサンプルコードをご紹介します。
test_countItemsを実行すると、シートのA列の項目のカウントを行います。
入力されている食べ物の各個数が表示されます。
コメント