If文

if文は最もよく使う構文だと思います。一般的な型の判定は忘れにくいですが、Collectionの判定については、どうだったかなと忘れることがあります。

  • 基本的な判定
Dim iTest As Integer
Dim strTest As String
Dim bTest As Boolean
Dim txtTest As TextBox

'ユーザ定義
Type UserType
strTest2 As String
iTest2 As Integer
End Type
Dim user As UserType

'値設定
iTest = 10
strTest = "TEST"
bTest = True

'数値判定
If iTest = 10 Then
'肯定文
End If

'文字列判定
If strTest = "TEST" Then
'肯定文
End If

'Boolean判定
If bTest = True Then
'肯定文
End If

'オブジェクト判定(Nothingでない場合)
If Not txtTest Is Nothing Then
'肯定文
strText = txtTest.Text
End If

'ユーザ定義判定(値設定の場合)
If Not Not user Then
'肯定文
strText = txtTest.Text
Else
'否定文
strText = ""
End If

'複数条件、折り返し(改行)、ElseIf判定
If (iTest = 10 Or iTest = 11) And bTest = True _
And strTest = "TEST" Then
'肯定文
ElseIf iTest >= 20 And iTest <= 30 Then
'否定文
ElseIf iTest >= 31 Then
'否定文
Else
'否定文
End If
  • 配列の判定
Dim strList(5) As String

'配列かどうかを判定する
If IsArray(strList) Then
'配列の場合
End If

'配列の要素数を判定する
If UBound(strList) == 5 Then
'最大要素添え字が5の場合
End If

※UBoundは配列の要素がない(0)場合は、エラーとなるので、配列の要素の初期化は前段としてやっておくことが必要です。もしくは内部別関数を作ってエラーキャッチして利用しましょう。

  • Collectionの判定
Dim colTest As Collection

'インスタンス化
Set colTest = New Collection

'要素追加
Call colTest.Add("KEY", "VALUE")


'要素数の判定
If colTest.Count = 1 Then
'要素数が1の場合
End If

'要素の有無(KEY)判定
If isExist(colTest,"KEY") Then
'KEYがある場合
End If

'コレクションの要素があるか判定を行う関数
Public Function isExist(ByRef col As Collection, ByRef strKey As String) As Boolean
  On Error GoTo NextErr
  Set getCol = col.Item(strKey)
  isExist = True
  Exit Function
NextErr:
isExist = False
End Function

※CollectionのKEYがあるかの判定は通常であればItemを参照時に存在しない場合エラーとなってしまうので、他にもやり方はありますが、上記のように内部関数(isExist)を別に作って判定しています。

またこれ以外にも要素取得、KEY設定時も同様にエラーが発生するケースがある為、別関数を作って呼び出して処理をするのが私の中の通例となっています。