【VBA】基本

変数

' 定義
Dim sample As Integer
Dim sample As Long
Dim sample As Double
Dim sample As String
Dim sample As Date
Dim sample As Boolean
Dim sample As Object
Dim sample As Variant
Dim sample    ' 指定なしはVariant型になる

' モジュール共通の変数(public)
public sample As String

' モジュール専用の変数(private)
private sample As String

' 複数
Dim a As Integer, b As String

' 代入
sample = 1
sample = "文字"
' 静的変数(プログラム実行中、値を保持)
Static sample As Integer

定数

Public/Privateを省略するとPrivate
Publicは標準モジュールにしか作れない

Const SAMPLE As String = "定数"
Public Const SAMPLE As String = "パブリック"

配列

Dim Sample(2) As String
        
Sample(0) = "りんご"
Sample(1) = "ゴリラ"
Sample(2) = "ラッパ"

Debug.Print Sample(0)  'りんご

別パターン

Dim Sample As Variant
Sample = Array(1, 2, "3")

' 全要素出力
Dim curValue As Variant
For Each curValue In Sample
    Debug.Print curValue
Next

セル選択範囲の値を配列に格納

' 複数セルでないとエラー
Dim arr_Temp() As Variant
set arr_Temp = Selection

' 単一セルでも可能、複数セルなら配列になる
Dim temp As Variant
set temp = Selection

コメント

' これはコメントです
Rem これはコメントです

IF文

If Sample = 1 Then
    MsgBox "1です"
ElseIf Sample = 2 And Sample = 3 Or Sample = 4 Then
    MsgBox  "2です"
Else
    MsgBox  "1,2以外です"
End If

'処理が1行の場合、1行で書ける
If Sample = 1 Then debug.print "1です"
IIF
    'IIF(条件, Trueの時, Falseの時)
    sample = IIf(A = 1, True, False)
Like
'*
If sample Like "高橋*" Then     '※0個以上の任意の文字
'?
If sample Like "高?" Then     '※任意の1文字
'#
If sample Like "高#" Then     '※1文字の数値(0~9)
'[ ]
If sample Like "[あ,い]" Then     '※[ ]内の1文字にマッチ
'[! ]
If sample Like "[!あ,い]" Then     '※[ ]内の1文字以外にマッチ
'[?-?]
If sample Like "[1-9]" Then     '※指定した範囲の1文字にマッチ

Select文

Select Case Sample
    Case 1
        MsgBox "1です"
    Case 2, 3
        MsgBox "2or3です"
    Case Else
        MsgBox "1~3以外です"
End Select

For文

For i = 1 To 3
    Debug.Print i & "回目"
Next
' 処理結果
' 1回目
' 2回目
' 3回目

Stepでiへの加算値を指定可能

For i = 1 To 3 Step 2
    Debug.Print i & "回目"
Next
' 処理結果
' 1回目
' 3回目

For Each文

配列、コレクションなどを終わりまで繰り返す

Dim arr As Variant
arr = Array(1, 2, "3")

Dim val As Variant
For Each val In arr
    Debug.Print val
Next

While文

条件がtrueの間ループ

i = 1
Do While i <= 3
    Debug.Print i & "回目"
    i = i + 1
Loop
' 処理結果
' 1回目
' 2回目
' 3回目

一回は通る

i = 1
Do
    Debug.Print i & "回目"
    i = i + 1
Loop While i <= 1
' 処理結果
' 1回目

Until文

条件に合致するまでループ

i = 1
Do Until i = 3
    Debug.Print i & "回目"
    i = i + 1
Loop
' 処理結果
' 1回目
' 2回目

一回は通る

i = 1
Do
    Debug.Print i & "回目"
Loop Until i = 1
' 処理結果
' 1回目

With

省略

With Worksheets("Sheet1")
    MsgBox .Cells(1, 1).Value
    MsgBox .Cells(1, 2).Value
End With

Exit

処理を抜ける

Exit Do
Exit For
Exit Function
Exit Sub

End

処理を終了する

End
End Function
End Sub

プロシージャ

Sub

戻り値がない
Public/Private省略でPublic
仮引数のByVal(値渡し)/ByRef(参照渡し)省略でByRef(参照渡し)

Sub Sample(aStr As String)
    MsgBox aStr
End Sub

'呼び出し方法
Sample "引数"        '※カッコつけない(カッコをつけると強制値渡しになる)
Call Sample("引数")
Function

戻り値がある(戻り値なしも作れる)
Public/Private省略でPublic
仮引数のByVal(値渡し)/ByRef(参照渡し)省略でByRef(参照渡し)

Function Sample(aStr As String) As String
    MsgBox aStr 
    Sample = "戻り値"     ' 戻り値はファンクション名に代入
End Function

'呼び出し方法
return = Sample("引数")

Enum

数値限定の定数をまとめる
Public/Private省略でPublic

Enum 支店番号
    A支店 = 100
    B支店        '省略すると連番になる
    Z支店 = 999
End Enum

Debug.Print 支店番号.A支店  '結果:100
Debug.Print 支店番号.B支店  '結果:101
Debug.Print 支店番号.Z支店  '結果:999
'値は省略できる
Public Enum enmClear
  None '値:0
  Clear    '値:1
  ClearContents   '値:2
End Enum

'入力内容を制限させる
Dim test As enmClear
test = Clear   '1が入力される

Type

ユーザー定義型。構造体
・Public/Private省略でPublic
・標準モジュールにしか作れない
・Collection、Dictionaryに入れられない
・値渡しでは引き渡せない

'ユーザー定義型
Private Type typeProfile
    id As Long
    name As String
    age As Long
End Type

'引数に設定可能
Sub test()
    Dim 代表者 As typeProfile
    Sample 代表者
End Sub

'戻り値に設定可能
Function Sample(aProfile As typeProfile) As typeProfile
    aProfile.id = 1
    aProfile.name = "高木"
    aProfile.age = 23
    
    Sample = aProfile
End Function

Collection

値やオブジェクトを格納する。
インデックスとキー(省略可)で指定可能。

Dim colls As New Collection
' 初期化するタイミングを自分で決める場合はこっち(Set)を使う
Dim colls As Collection
Set colls = New Collection

'全件処理
Dim v As Variant
For Each v In colls
    Debug.Print v
Next
操作 コマンド
追加 col.Add "item1"
col.Add "item2", "key2"
使用 col(1)
col("key2")
削除 col.Remove 1
col.Remove "key2"
カウント col.Count

Dictionary

値とキーをセットで格納する。
キーは重複できない。
存在確認がメソッドで可能。
(参照設定)

Dim dic As New Dictionary
' 初期化するタイミングを自分で決める場合はこっち(Set)を使う
Dim dic As Dictionary
Set dic = New Dictionary

'参照設定不要
Dim dic As Object
Set dic = CreateObject("Scripting.Dictionary")

'全件処理
Dim v As Variant
For Each v In dic
    Debug.Print v
    Debug.Print dic(v)
Next
操作 コマンド
追加 dic.Add "key1", "item1"
使用 dic("key1")
削除 dic.Remove("key1")
値変更(項目) dic("key1") = 1000
値変更(キー) dic.Key("key1") = "key1000"
カウント dic.Count
存在確認 dic.Exists("key1")
配列に格納(項目) array = dic.keys
配列に格納(キー) array = dic.items

GoTo

ラベル先へ処理をジャンプさせる

    '入力件数のチェック
    If colDir.Count = 0 Then
        '0件の場合エラー
        errMsg = "対象のディレクトリを入力してください"
        GoTo ErrorEnd 'ErrorEndに飛ぶ
    End If

Exit Sub '←これがないとErrorEndが必ず実行される

ErrorEnd:
    MsgBox errMsg, vbCritical
    
End Sub