Windows 10 Pro_x64 + Excel2013_x86 VBA の ListBox で複数の列を表示する

Windows 10 Pro_x64 + Excel2013_x86 VBA の ListBox で複数の列を表示する
 
Excel VBA のUserForm上のListBoxに複数列を表示したい時のメモ
普段はデータベースからひらってきたデータを表示することが多いんだけど
最小限必要なコードを張りつけてみる
 
・UserFormを1個追加する(UserForm2)
・UserForm2の上にListBoxを1個追加する
・UserForm2の上にCommandButtonを3個追加する
・CommandButton1-3をクリックしたときにListBox1に対応するデータを追加する
・ListBox1をダブルクリックしたときに、対象データを表示する
対象データは以下の全国一括(KEN_ALL.CSV)より一部抜粋
郵便番号データダウンロード
サンプルコード


Option Explicit

Private Sub CommandButton1_Click()
Call SetPostal("01")
End Sub

Private Sub CommandButton2_Click()
Call SetPostal("02")
End Sub

Private Sub CommandButton3_Click()
Call SetPostal("03")
End Sub

Private Sub SetPostal(ByRef aPrefCode As String)
'
ListBox1.Clear
ListBox1.ColumnWidths = "30 pt;40 pt;70 pt;100 pt"
ListBox1.ColumnCount = 4
'
Select Case aPrefCode
Case "01"
ListBox1.AddItem ""
ListBox1.List(0, 0) = "01101"
ListBox1.List(0, 1) = "0640954"
ListBox1.List(0, 2) = "札幌市中央区"
ListBox1.List(0, 3) = "宮の森四条"
ListBox1.AddItem ""
ListBox1.List(1, 0) = "01102"
ListBox1.List(1, 1) = "0028071"
ListBox1.List(1, 2) = "札幌市北区"
ListBox1.List(1, 3) = "あいの里一条"
Case "02"
ListBox1.AddItem ""
ListBox1.List(0, 0) = "02201"
ListBox1.List(0, 1) = "0301271"
ListBox1.List(0, 2) = "青森市"
ListBox1.List(0, 3) = "六枚橋"
ListBox1.AddItem ""
ListBox1.List(1, 0) = "02202"
ListBox1.List(1, 1) = "0361516"
ListBox1.List(1, 2) = "弘前市"
ListBox1.List(1, 3) = "藍内"
Case "03"
ListBox1.AddItem ""
ListBox1.List(0, 0) = "03201"
ListBox1.List(0, 1) = "0200886"
ListBox1.List(0, 2) = "盛岡市"
ListBox1.List(0, 3) = "若園町"
ListBox1.AddItem ""
ListBox1.List(1, 0) = "03202"
ListBox1.List(1, 1) = "0270202"
ListBox1.List(1, 2) = "宮古市"
ListBox1.List(1, 3) = "赤前"
End Select
'
End Sub

Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
'
Dim setVal1 As String
Dim setVal2 As String
Dim setVal3 As String
Dim setVal4 As String
'
If ListBox1.ListIndex >= 0 Then
setVal1 = ListBox1.List(ListBox1.ListIndex, 0)
setVal2 = ListBox1.List(ListBox1.ListIndex, 1)
setVal3 = ListBox1.List(ListBox1.ListIndex, 2)
setVal4 = ListBox1.List(ListBox1.ListIndex, 3)
End If
'
Debug.Print setVal1, setVal2, setVal3, setVal4
'
End Sub