Excel VBA2

Select: Whenのようにcaseを書いていく構文です。

Sub SelectTest()
    Dim signal As String
    signal = Range("a1").Value
    
    Dim result As Range
    Set result = Range("a2")
    
    Select Case signal
    
    Case "red"
        result.Value = "Stop!"
    Case "green"
        result.Value = "Go"
    Case "yellow"
        result.Value = "Caution"
    Case Else
        result.Value = "n.a"
        
    End Select
    
End Sub

while文

Sub WhileTest()
    Dim i As Integer
    i = 1
    
    Do While i < 10
        Cells(i, 1).Value = i
        i = i + 1
    Loop
End Sub

For文

Sub ForTest()
    Dim i As Integer
    
    For i = 1 To 9
        Cells(i, 2).Value = i
    Next i

End Subl

ForEachによるループ

Sub EachTest()
    Dim names As Variant
    names = Array("yamada", "taro", "sakamoto")
    
    For Each Name In names
        Debug.Print Name
    Next Name
End Sub

プロシージャの呼び出し

Sub CallTest()
    Dim names As Variant
    names = Array("okamoto", "nakamura", "hayashi")
    
    For Each name In names
        Call SayHi(name)
    Next name
End Sub

Sub SayHi(ByVal name As String)
 Debug.Print "hi, " & name
End Sub

返り値を返すfunctionプロシージャ

Sub CallTest()
    Dim names As Variant
    names = Array("okamoto", "nakamura", "hayashi")
    
    For Each name In names
        Debug.Print SayHi(name)
    Next name
End Sub

Function SayHi(ByVal name As String)
  SayHi = "hi, " & name
End Function

成績表 :一定数以下の数字をカウントして、メッセージ表示

Sub FindLowScores()
    Dim i As Long
    Dim n As Long
    i = 2
    n = 0
    
    Do While Cells(i, 1).Value <> ""
        If Cells(i, 2).Value < 40 Then
            Cells(i, 2).Interior.Color = vbRed
            n = n + 1
        End If
        i = i + 1
        Loop
    
    MsgBox (n & "件該当しました!")

End Sub

a