Excel VBA 基本文法まとめ
仕事の中で結構EXCEL VBAを書く機会があります。
忘れないように基本構文をここに覚書きしておきます。
関数宣言
#戻り値が必要な関数 Function funcA( X As Integer ) As Integer <処理> funcA = 1 End Function #戻り値が不要な関数 Sub funcB( X As Integer ) <処理> End Sub #呼び出し例 Dim X As Integer X = funcA( 0 ) Call funcB( 1 )
変数宣言
#記入法① Dim <変数名> As Integer Dim <変数名> As Long Dim <変数名> As Double Dim <変数名> As Boolean Dim <変数名> As String Dim <変数名> As Date Dim <変数名> As Object Dim <変数名> As Variant(全ての型) #記入法② Dim <変数名> As Integer, <変数名> As Long #記入法③ Dim <変数名> ※As <型>を省略するとVariantで解釈される #記入法④(初期値の代入) Dim <変数名> As Integer: <変数名>=0
Boolean型のサンプル
True / Falseで表現する
Dim X As Boolean, Y As Boolean X = True Y = False
Date型のサンプル
Date 今日の日付
Time 現在の時刻
#本日の日付の文字列表現 (20170120) Dim X As String X = Format(Date, "yyyymmdd") #現在の時刻が15時〜16時の間の時という条件式 If Time < TimeValue("15:00:00") And Time > TimeValue("16:00:00") Then <処理> End If
if文
If <条件文> Then <処理> Else IF <条件文> Then <処理> Else <処理> End If
for文
For〜Nextで繰り返し文を表現する。
Exit Forはbreakを表現する
For i = 0 To 10 If <条件式> Then Exit For End If Next
while文
Do While〜Loopで繰り返し文を表現する。
DoEventsはCPUのクロックの占有を一時解放する。
※これをしないとループ中に処理を占有して他の処理ができない。
Do While <条件文> <処理> DoEvents Loop
複数条件式
Andで「かつ」、Orで「または」を表現する
<条件式> And <条件式> <条件式> Or <条件式>
否定文
条件式の前にNotをつける
If Not <条件式> Then <処理> End If