エクセルVBAマクロの解説: H列の〇の数を数える


エクセルVBAマクロの解説: H列の〇の数を数える

はじめに

 エクセルのVBA(Visual Basic for Applications)を使用して、H列にある特定の文字(例: 〇)の数を数えるマクロを作成しました。このマクロは、特定のシートに対して実行され、H列内の指定した文字の出現回数をカウントします。

Sub CountOccurrencesInColumnH()

    Dim ws As Worksheet

    Dim cell As Range

    Dim targetColumn As Range

    Dim count As Long

    Dim targetValue As String

    

    ' 対象のシートと列を指定

    Set ws = ThisWorkbook.Sheets("Sheet1 (2)") ' シート名を適切に変更

    Set targetColumn = ws.Range("H1:H" & ws.Cells(ws.Rows.count, "H").End(xlUp).Row)

    targetValue = "〇" ' カウントしたい文字を指定

    

    ' カウント

    count = Application.WorksheetFunction.CountIf(targetColumn, targetValue)

    

    ' 結果を表示

    MsgBox "H列には " & count & " 個の " & targetValue & " があります。", vbInformation, "カウント結果"

End Sub


コードの解説

以下に、上記のコードの各部分を解説します。

  1. シートと列の指定:

    Set ws = ThisWorkbook.Sheets("Sheet1 (2)") ' シート名を適切に変更
    Set targetColumn = ws.Range("H1:H" & ws.Cells(ws.Rows.count, "H").End(xlUp).Row)
    
    • ThisWorkbook.Sheets("Sheet1 (2)") で対象のシートを指定します。シート名は適切に変更してください。
    • targetColumn にはH列の範囲を設定します。
  2. カウント処理:

    count = Application.WorksheetFunction.CountIf(targetColumn, targetValue)
    
    • Application.WorksheetFunction.CountIf を使用して、指定した文字の出現回数をカウントします。
  3. 結果の表示:

    MsgBox "H列には " & count & " 個の " & targetValue & " があります。", vbInformation, "カウント結果"
    
    • MsgBox を使用して、カウント結果をメッセージボックスで表示します。

まとめ

 このマクロを使用することで、H列に含まれる指定した文字の数を簡単にカウントできます。必要に応じてシート名やカウントしたい文字を変更してください。