目次
1. 論理演算子とは?
論理演算子は、条件式を組み合わせるために使用されます。条件分岐 (If
文) やループ処理 (Do While
など) で活用できます。
2. 各論理演算子の説明
(1) And(かつ)
両方の条件が 真 (True) の場合に True
を返します。
Dim a As Integer: a = 10
Dim b As Integer: b = 20
If a > 5 And b < 30 Then
MsgBox "両方の条件が成立しています"
End If
(2) Or(または)
どちらか一方でも 真 (True) なら True
を返します。
Dim x As Integer: x = 5
Dim y As Integer: y = 50
If x < 10 Or y > 100 Then
MsgBox "いずれかの条件が成立しています"
End If
(3) Not(否定)
条件の真偽を反転させます。
Dim flag As Boolean: flag = False
If Not flag Then
MsgBox "flag は False なので、条件が成立"
End If
(4) Xor(排他的論理和)
片方の条件が True
で、もう片方が False
の場合に True
を返します。
Dim a As Boolean: a = True
Dim b As Boolean: b = False
If a Xor b Then
MsgBox "どちらか一方が True なので成立"
End If
3. 論理演算子を活用した条件分岐の例
(1) And を使った複数条件のチェック
Dim score As Integer: score = 85
If score >= 80 And score <= 100 Then
MsgBox "成績は優秀です"
End If
(2) Or を使ったいずれかの条件のチェック
Dim weather As String: weather = "雨"
If weather = "雨" Or weather = "雪" Then
MsgBox "傘を持っていきましょう"
End If
(3) Not を使った条件の反転
Dim isHoliday As Boolean: isHoliday = False
If Not isHoliday Then
MsgBox "今日は平日です"
End If
4. まとめ
- And:両方
True
の場合に成立 - Or:どちらか
True
なら成立 - Not:条件を反転
- Xor:どちらか一方が
True
の場合に成立
条件分岐やループと組み合わせることで、柔軟な処理を実装できます。
コメント