ユーザー定義変数とは異なる型の変数を一つの変数で取り扱えるようになる仕組みです。 Type~End Typeの間に各変数を指定して配列と同じように要素番号を指定して宣言します。
Type ユーザー定義変数名
変数名1 As 型
変数名2 As 型
変数名3 As 型
End Type
Dim 変数名(要素番号) As ユーザー定義変数名
以下のサンプルコードではユーザー定義変数に値をセットして値を表示させています。
Type UserInfo
Name As String
Address As String
Tel As String
Age As Integer
End Type
Sub SetType()
Dim typUser(2) As UserInfo
With typUser(0)
.Name = "テスト 一郎"
.Address = "東京都"
.Tel = "0000-0000-0001"
.Age = 20
End With
With typUser(1)
.Name = "テスト 次郎"
.Address = "神奈川県"
.Tel = "0000-0000-0002"
.Age = 21
End With
With typUser(2)
.Name = "テスト 三郎"
.Address = "埼玉県"
.Tel = "0000-0000-0003"
.Age = 23
End With
For i = 0 To UBound(typUser)
strMsg = strMsg & typUser(i).Name & ":" & typUser(i).Address _
& ":" & typUser(i).Tel & ":" & typUser(i).Age & vbCrLf
Next
MsgBox strMsg
End Sub
以下では【Sheet1】のセルに格納された値を取得してユーザー定義変数に格納しています。
セルの値 |
---|
Type UserInfo
Name As String
Address As String
Tel As String
Age As Integer
End Type
Sub SetType()
Dim typUser(2) As UserInfo
For i = 0 To UBound(typUser)
With typUser(i)
.Name = Worksheets("Sheet1").Cells(i + 2, 1)
.Address = Worksheets("Sheet1").Cells(i + 2, 2)
.Tel = Worksheets("Sheet1").Cells(i + 2, 3)
.Age = Worksheets("Sheet1").Cells(i + 2, 4)
End With
Next
For i = 0 To UBound(typUser)
strMsg = strMsg & typUser(i).Name & " : " & typUser(i).Address _
& " : " & typUser(i).Tel & " : " & typUser(i).Age & vbCrLf
Next
MsgBox strMsg
End Sub