備忘録

webの備忘録のために

はじめてのVBA その4

VBAではIf分も書ける。

Sub IfTest()

    If Range("a1").Value > 80 Then
        Range("a2").Value = "OK!"
    ElseIf Range("a1").Value > 60 Then
        Range("a2").Value = "soso..."
    Else
        Range("a2").Value = "NG!"
    End If


End Sub

VBAでは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

VBAではWhile分だって。

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

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

End Sub

基本的なif、ループ系に関しても全然使える。 書き方だけは各々特徴がある感じだけども。