Excel VBAコース(8):Excel VBA言語基本 - データ型(Data type)、データ構造(Data structure)
この記事では、Excel VBA言語の基本的なデータ型(Data type)と提供されるデータ構造(Data structure)について説明します。
前の記事で続く内容だ。
Excel VBAコース(7):Excel VBA言語基本 - 文法(Syntax)
3.3。データ型
3.3.1.基本データ型
VB(またはVBA)でサポートされているデータ型をまとめると、次の表のようになります。以下のソースの表の内容のうち、コレクション、辞書は「資料構造」で別々に説明されています。
基本データ型一覧
ソース: https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/data-type-summary
| データ型 | ストレージ容量 | 範囲 |
| Boolean | 2 bytes | True または False |
| Byte | 1 byte | 0 ~ 255 |
| コレクション | Unknown | Unknown |
| Currency (scaled integer) | 8 bytes | -922,337,203,685,477.5808 ~ 922,337,203,685,477.5807 |
| 日付 | 8 bytes | January 1, 100, to December 31, 9999 (100-01-01 ~ 9999-12-31) |
| Decimal | 14 バイト | +/-79,228,162,514,264,337,593,543,950,335 with no decimal point +/-7.9228162514264337593543950335 with 28 places to the right of the decimal Smallest non-zero number is+/-0.00000000000000000000000000001 |
| Dictionary | Unknown | Unknown |
| Double (double-precision floating-point) | 8 bytes | -1.79769313486231E308 to -4.94065645841247E-324 for negative values 4.94065645841247E-324 to 1.79769313486232E308 for positive values |
| Integer | 2 bytes | -32,768〜32,767 |
| 長い (Long integer) | 4 bytes | -2,147,483,648〜2,147,483,647 |
| LongLong (LongLong integer) | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Valid on 64-bit platforms only. |
| LongPtr (Long integer on 32-bit systems, LongLong integer on 64-bit systems) | 4 bytes on 32-bit systems 8 bytes on 64-bit systems | -2,147,483,648 to 2,147,483,647 on 32-bit システム -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit システム |
| Object | 4 bytes | Any Object reference |
| シングル (single-precision floating-point) | 4 bytes | -3.402823E38 to -1.401298E-45 for negative values 1.401298E-45 to 3.402823E38 for positive values |
| String (variable-length) | 10 bytes + string length | 0 to approximately 2 billion |
| String (fixed-length) | Length of string | 1 to approximately 65,400 |
| Variant (with numbers) | 16 バイト | Any numeric value up to the range of a Double |
| Variant (with characters) | 22 bytes + string length (24 bytes on 64-bit systems) | Same range as for variable-length String |
| User-defined (using タイプ) | Number required by elements | The range of each element is the same as the range of its data type. |
この中で最もよく使われるデータ型は、Int、Long、String、Boolean程度である。
Variant、User−definedデータ型について、以下にさらに説明する。
Variant データ型
Variantデータ型は、複数のデータ型を保存して処理できる特別なデータ型です。変数を宣言するときにデータ型を省略すると、Variantデータ型として指定されます。 Variantデータ型の詳細については、以下のURLを参照してください。
https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/variant-data-type
実行中にVariant変数がどのデータ型を格納しているかを確認するには、VarType関数を使用します。
https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/vartype-function
構文
VarType(varname)
必須要素 varname 引数は、ユーザー定義型の変数を除く変数を含むVariantです。
返すフォーマット
| 定数 | 値 | 説明 |
| vbEmpty | 0 | Empty(初期化されていない) |
| vbNull | 1 | ヌル(有効なデータなし) |
| vbInteger | 2 | 整数 |
| vbLong | 3 | 長い整数 |
| vbSingle | 4 | 単精度浮動小数点数 |
| vbDouble | 5 | 倍精度浮動小数点数 |
| vbCurrency | 6 | 通貨値 |
| vbDate | 7 | 日付値 |
| vbString | 8 | 文字列 |
| vbObject | 9 | オブジェクト |
| vbError | 10 | エラー値 |
| vbBoolean | 11 | Boolean 値 |
| vbVariant | 12 | Variant(variant 配列でのみ使用) |
| vbDataObject | 13 | データアクセスオブジェクト |
| vbDecimal | 14 | 10進値 |
| vbByte | 17 | バイト値 |
| vbArray | 8192 | 配列 |
私は個人的にVariantデータ型をうまく使用せず、シートデータを一度に読み書きするときにのみ主に使用します。 Variant arryを使用して大量のシートデータを読み書きする方法については、以下の記事を参照してください。
VBAコーディングパターン:Range Loop - 読み取り(Read)
VBAコーディングパターン:Range Loop - Write
Variantデータ型を使用するサンプルコードです。整数、文字列、実数、日付データ型をすべて処理できることを示します。
Sub VariantTest()
Dim a As Variant '데이터 형식을 생략하면 Variant 형식임
a = 1: Debug.Print a
a = "1": Debug.Print a
a = 1.1: Debug.Print a
a = CDate("2021-07-31"): Debug.Print a
End Sub
User-defined(ユーザー定義)データ型
カスタムデータ型を宣言して使用できます。 C言語の「struct」に似た「Type」キーワードでカスタムデータ型を宣言します。 User-defined データ型はオブジェクトではなく、宣言するとすぐに instance が生成され、メモリが割り当てられ、値を入力できるようになります。
User-definedデータ型の詳細については、以下のURLを参照してください。
https://docs.microsoft.com/en-us/office/vba/language/how-to/user-defined-data-type
User-defined データ型のサンプルコードは次のとおりです。
Type EmployeeRecord ' 사용자 정의 형식을 만듭니다.
ID As Integer ' 데이터 형식의 요소를 정의합니다.
Name As String
Address As String
Phone As Long
HireDate As Date
End Type
Sub CreateRecord()
Dim MyRecord As EmployeeRecord ' 변수를 선언합니다.
MyRecord.ID = 12003 ' 요소에 값을 할당합니다.
MyRecord.Name = "Andy"
MyRecord.HireDate = CDate("2021-07-31")
End Sub
3.3.2。データ構造
よく使うデータ構造はArray、Collection、Dictionaryがある。それぞれについて見てみましょう。
Array
固定数の Item を持つ。オブジェクトではなく宣言すると、インスタンスが生成されます。宣言時に次元の数と各次元の下限、上限範囲を指定することもでき、実行時に動的に配列の次元、範囲を変更することもできる。各次元の下限と上限を指定せずにitemの数だけを指定する場合、デフォルトでは下限は0です。 Option Base 1を使用すると、デフォルトの下限は1になります。
宣言の例コード
Dim DayArray(50) Dim Matrix(3, 4) As Integer Dim MyMatrix(1 To 5, 4 To 9, 3 To 5) As Double
各次元の下限値/上限値宣言、確認:LBound、UBoundを使用
Dim A(1 To 100, 0 To 3, -3 To 4) LBound(A, 1) -> 1, UBound(A, 1) -> 100 ' 1차원 하한/상한 LBound(A, 2) -> 0, UBound(A, 2) -> 3 ' 2차원 하한/상한 LBound(A, 3) -> -3, UBound(A, 3) -> 4 ' 3차원 하한/상한
ディメンションサイズの変更:Redimステートメントで動的配列のディメンションサイズを変更します。
Dim MyArray() As Integer ' 동적 배열을 선언합니다. Redim MyArray(5) ' 5개의 요소를 할당합니다. Redim Preserve MyArray(15) ' 15개의 요소로 크기를 변경합니다.
Item Loop(For Next)
'Split & Trim 처리
Public Function SplitTrim(aExpression As String, aDelimeter As String) As String()
Dim saOut() As String, i As Integer
saOut = Split(aExpression, aDelimeter)
For i = LBound(saOut) To UBound(saOut)
saOut(i) = Trim(saOut(i))
Next i
SplitTrim = saOut
End Function
初期化:Erase文で配列変数を初期化します。
' 배열 변수를 선언합니다.
Dim NumArray(10) As Integer ' 정수 배열입니다.
Dim StrVarArray(10) As String ' 변수 문자열 배열입니다.
Dim StrFixArray(10) As String * 10 ' 고정 문자열 배열입니다.
Dim VarArray(10) As Variant ' Variant 배열입니다.
Dim DynamicArray() As Integer ' 동적 배열입니다.
ReDim DynamicArray(10) ' 저장 공간을 할당합니다.
Erase NumArray ' 0으로 지정된 각 요소입니다.
Erase StrVarArray ' 길이가 0인 문자열 ("")로 지정된 각 요소입니다.
Erase StrFixArray ' 0으로 지정된 각 요소입니다.
Erase VarArray ' Empty로 지정된 각 요소입니다.
Erase DynamicArray ' 배열에 의해 사용되는 빈 메모리입니다.
コレクション
コレクションクラスは動的配列と似ています。可変個数の unique item を Add, Remove できる。オブジェクトだから」セット「」と「New」キーワードを使用してインスタンスを作成します。 Visual Basic言語でオブジェクトに参照を作成したり、新しい参照を割り当てるときは必ず「セット” keyword を使用しなければならず、変数に値を割り当てるときは “Set” keyword は必要ない。オブジェクトを扱う時と変数を扱う時をよく区別しなければ文法エラーは発生しない。よく間違いがあるので注意が必要です。
コレクションオブジェクトの宣言、インスタンスの作成、アイテムの追加などのタスク固有のコードについては、次の表を参照してください。
| Task | サンプルコード |
| 宣言 | Dim oCol As Collection |
| Instanceの作成 | Set oCol = New Collection |
| 宣言と同時にインスタンスを作成する | Dim oCol As New Collection |
| アイテムを追加 | oCol.Add “Apple” |
| IndexによるItemへのアクセス | oCol(1) |
| アイテム数 | oCol.Count |
| アイテムループ(For) | Dim l As Long For l = 1 to oCol.Count Debug.Print oCol(l) Next |
| アイテムループ(For Each) | Dim fruit As Variant For Each fruit in oCol Debug.Print fruit Next |
| アイテムの削除(インデックス指定) | oCol.Remove(1) |
| Instanceの削除 | Set oCol = Nothing |
Collection を使用するコード例は次のとおりです。ちなみに、コレクションのアイテムは1から始まります。
Sub CollectionTest()
Dim oCol As Collection
Set oCol = New Collection
oCol.Add "Apple"
oCol.Add "Strawberry"
oCol.Add "Lemon"
oCol.Add "Banana"
Debug.Print oCol(1)
Debug.Print oCol.Item(1)
Debug.Print "----------"
Dim l As Long
For l = 1 To oCol.Count
Debug.Print oCol(l)
Next
Debug.Print "----------"
oCol.Remove (1)
Dim fruit As Variant
For Each fruit In oCol
Debug.Print fruit
Next
Set oCol = Nothing
End Sub
'출력
Apple
Apple
----------
Apple
Strawberry
Lemon
Banana
----------
Strawberry
Lemon
Banana
Dictionary
Key-Value構造の可変unique Itemを管理でき、itemを動的にAdd/Removeすることができる。
Python言語のDictionary、C++のHashMap、JavaのHashMapと同様のデータ構造である。キー値に近づくと、パフォーマンスはO(1)レベルです。
辞書クラスは基本的には提供されていません。 Early binding 方式で使用するには、まず「Microsoft Scripting Runtime」を参照する必要があります。 Late binding 方式で使用するには CreateObject を通じて instance を生成して使用します。
Dictionaryオブジェクト宣言、インスタンス生成、Item追加などのタスク固有のコードについては、次の表を参照してください。
| Task | サンプルコード |
| 宣言(early binding) | Dim oDic As Dictionary |
| Instanceの作成(early binding) | Set oDic = New Dictionary |
| 宣言 (late binding) | Dim oDic As Object |
| Instance の生成 (late binding) | Set oDic = CreateObject(“Scripting.Dictionary”) |
| アイテムを追加 | oDic.Add “Apples”, 50 |
| 値の変更 | oDic(“Apples”) = 60 |
| 値を取得 | appleCount = oDic(“Apples”) |
| Keyが存在することを確認する | oDic.Exists(“Apples”) |
| アイテムの削除 | oDic.Remove(“Apples”) |
| すべてのアイテムを削除 | oDic.RemoveAll |
| アイテム数 | oDic.Count |
| アイテムループ(For Each) | Dim key As Variant For Each key in oDic.Keys Debug.Print key, oDic(key) 次のキー |
| Item Loop (For, Early binding only) | Dim l As Long For l = 0 To oDic.Count -1 Debug.Print oDic.Keys(l), oDic.Items(l) Next l |
Dictionaryを使用する例のコードは次のとおりです。ちなみに、DictionaryのItemsは0から始まる。
Sub DictionaryTest()
Dim oDic As Dictionary
Set oDic = New Dictionary
oDic.Add "A", "Apple"
oDic.Add "S", "Strawberry"
oDic.Add "L", "Lemon"
oDic.Add "B", "Banana"
Debug.Print oDic("A")
Debug.Print oDic.Items(0)
Debug.Print "----------"
Dim l As Long
For l = 0 To oDic.Count - 1
Debug.Print oDic.Items(l)
Next
Debug.Print "----------"
oDic.Remove ("A")
Dim key As Variant, fruit As String
For Each key In oDic.Keys
fruit = oDic(key)
Debug.Print fruit
Next
Set oDic = Nothing
End Sub
'출력
Apple
Apple
----------
Apple
Strawberry
Lemon
Banana
----------
Strawberry
Lemon
Banana
DictionaryオブジェクトをFor Loop構文で検索するときにキー値を含む変数は、Variant型またはObject型のみです。上記の例では、23行目と24行目のコードではVariant形式を使用しています。
この記事では、VBAデータ型とデータ構造について説明しました。特にCollectionとDictionaryはよく使う可能性が非常に高いので、よく煮ておきたい。次に、VBAコーディング時に知っておくと良いHow-Toについて見てみましょう。
<<関連記事一覧>>
- Excel VBAコースを開始します。 (講座予告、feat.Excel VBAを推奨する理由)
- Excel VBAコース(1):Excel VBAの概要
- Excel VBAコース(2):Excel VBAの基礎
- Excel VBAコース(3):Excel Object Model
- Excel VBAコース(4):Excel Object Modelを扱う
- Excel VBAコース(5):Excelファイル拡張子、VBE、フォント設定
- Excel VBAコース(6):Excel VBA言語基本 - 変数
- Excel VBAコース(7):Excel VBA言語基本 - 文法(Syntax)
- Excel VBAコース(8):Excel VBA言語基本 - データ型(Data type)、データ構造(Data structure)
- Excel VBAコース(9):Excel VBA How-To
- Excel VBAコース(10):Excel VBAで開発され使用されているツール
- Excel VBAコース全体目次








