[[20200630102931]] 『VBA 複数列のリストボックスの件数を取得する。』(フォーキー) ページの最後に飛ぶ

[ 初めての方へ | 一覧(最新更新順) | 全文検索 | 過去ログ ]

 

『VBA 複数列のリストボックスの件数を取得する。』(フォーキー)

お世話になります。

ワークシートのA列に数値が入っており、条件に一致すればB列の値をリストボックスの1列目に、C列を2列目に、D列を3列目に転記するマクロを作成しました。

条件に一致してもC列、D列は空欄の場合もあります。

 Private Sub UserForm_Initialize()
     Dim i As Long
     Dim Last As Long
     Dim c As Long

     Last = Cells(Rows.Count, 1).End(xlUp).Row

     With Me

         .ListBox1.ColumnCount = 3
         .ListBox1.ColumnWidths = "20;20;20"

         For i = 2 To Last
             If Cells(i, 1).Value > 2 And Cells(i, 2).Value <> "" Then
                 c = .ListBox1.ListCount
                 .ListBox1.AddItem ""
                 .ListBox1.List(c, 0) = Cells(i, 2).Value
                 .ListBox1.List(c, 1) = Cells(i, 3).Value
                 .ListBox1.List(c, 2) = Cells(i, 4).Value
             End If
         Next
     End With
 End Sub

本題ですが、複数列のリストボックスにて、1列目は何件、2列目は何件……、または全部の合計を出す方法がわかりません。
ご教授お願い致します。

< 使用 Excel:Excel2010、使用 OS:Windows10 >


 >1列目は何件、2列目は何件…

 1列目と2列目が違うと言うことは、空白は数えないと言うことなんですね。

 地道にカウントする案

 Private Sub UserForm_Initialize()
     Dim i As Long
     Dim Last As Long
     Dim c As Long
     Dim BCD(2) As Long ’カウント用

     Last = Cells(Rows.Count, 1).End(xlUp).Row
     With Me
         .ListBox1.ColumnCount = 3
         .ListBox1.ColumnWidths = "20;20;20"
         For i = 2 To Last
             If Cells(i, 1).Value > 2 And Cells(i, 2).Value <> "" Then
                 c = .ListBox1.ListCount
                 .ListBox1.AddItem ""
                 .ListBox1.List(c, 0) = Cells(i, 2).Value
                 .ListBox1.List(c, 1) = Cells(i, 3).Value
                 .ListBox1.List(c, 2) = Cells(i, 4).Value

                 BCD(0) = BCD(0) + 1
                 BCD(1) = BCD(1) + IIf(IsEmpty(Cells(i, 3).Value), 0, 1)
                 BCD(2) = BCD(2) + IIf(IsEmpty(Cells(i, 4).Value), 0, 1)

             End If
         Next
     End With

     Debug.Print BCD(0), BCD(1), BCD(2)
 End Sub

(半平太) 2020/06/30(火) 12:14


半平太さんありがとうございます。
IsEmpty関数で空欄かそうでないかを判定して、カウントしているんですね。
IIf関数も初めて知りました。Ifを使用して判定するより式がすっきりして見えます。
勉強になりました。ありがとうございます。
(フォーキー) 2020/06/30(火) 12:43

コメント返信:

[ 一覧(最新更新順) ]


YukiWiki 1.6.7 Copyright (C) 2000,2001 by Hiroshi Yuki. Modified by kazu.