0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

備忘録 - IF構文 【VBA】

0
Posted at

基本構文

条件に合致する際の処理のみ書く場合

If 条件 Then
 条件に合致する場合の処理
End If

条件に合致する場合としない場合を書く場合

If 条件 Then
 条件に合致する場合の処理
Else
 条件に合致しない場合の処理
End 

複数の条件を書く場合

If 条件1 Then
 条件1に合致する場合の処理
Elseif 条件2 Then
 条件2に合致する場合の処理
Else
 どの条件にも合致しない場合の処理
End 

End Ifの省略

'条件分けがない場合、End Ifを省略し、1行で書くこともできる
If 条件 Then 条件が合致する場合の処理

GoToステートメント

条件に合致した場合、ラベルまで飛んで処理を行う。条件に合致しなかった場合は、ラベルまで飛んで処理を行う。主にエラー時の動作などを指定。

Sub プロシージャ名
If 条件 Then GoTo ラベル
 条件に合致した場合の処理
Exit Sub ' 条件に合致した場合はここで処理が終わる
 
ラベル:
 条件に合致しなかった場合の処理
End Sub

具体例

Sub myVBA()

 Dim myRange As Range
 Set myRange = Range("B3")
    
 If VBA.IsError(myRange.Value) Then GoTo Getout
  Range("C3").Value = myRange.Value
 Exit Sub

 Getout:
  Debug.Print "myRangeにエラーがあります"
End Sub
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?