0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Windows 10 Pro x64 + Excel2016 x86 VBA の ComboBox で複数の列を表示する

Posted at

目的

Excel VBA のUserForm上のComboBoxに複数列を表示したい時のメモ
普段はデータベースからひらってきたデータを表示することが多いんだけど
最小限必要なコードを張りつけてみる

作成手順

・UserFormを1個追加する
・UserFormの上にComboBoxを1個追加する
・UserFormの上にCommandButtonを2個追加する
・CommandButton1をクリックしたときにComboBox1にデータを追加する
・CommandButton2をクリックしたときにComboBox1で選択されている
 データを表示する
対象データは郵便番号データダウンロードの全国一括(KEN_ALL.CSV)より一部抜粋

サンプルコード

Option Explicit

Private Sub CommandButton1_Click()

    Dim varArry()   As Variant
    
    ReDim varArry(3, 2)

    varArry(0, 0) = "01"
    varArry(0, 1) = "北海道"
    varArry(1, 0) = "02"
    varArry(1, 1) = "青森県"
    varArry(2, 0) = "03"
    varArry(2, 1) = "岩手県"
'
    ComboBox1.Clear
'
    With ComboBox1
        .ColumnCount = 2            '1行に2個表示
        .TextColumn = 2             '2個目のデータを表示
        .BoundColumn = 1            '※1参照
        .ColumnWidths = "30, 50"    'カラムの幅
        .List() = varArry()         'リスト項目の設定
    End With

End Sub

Private Sub CommandButton2_Click()
'
    Dim strCode     As String
    Dim strName     As String
'
    If ComboBox1.ListIndex >= 0 Then
        strCode = Trim(ComboBox1.Column(0, Me.ComboBox1.ListIndex))
        strName = Trim(ComboBox1.Column(1, Me.ComboBox1.ListIndex))
    End If
'
Debug.Print strCode, strName
'
End Sub

※1
0 コントロールに ListIndex プロパティの値を割り当てます。
1 以上指定した列からコントロールに値を割り当てます。このプロパティを
 使用するとき、列には、1 から番号が付けられます (既定)。

参考にしたのは以下のサイト

"BoundColumn/連結列" プロパティ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?