IT系/VBA/基本/繰り返し処理

Last-modified: 2020-08-08 (土) 09:12:16

目次


概要

繰り返し処理に関するVBAのTIPS。になればよいけどリンク集。

繰り返し処理

  • For文
    Dim i As Integer
    For i = 0 To 4
        If i <> "" Then
            Exit For
        End If
    Next
  • Do While文
    Dim i As Integer: i = 0
    Do While i < 5
       If i = 3 Then
           Exit Do
       End If
       i = i + 1
    Loop
  • Do Until文
    Dim isOk As Boolean: isOk = False
    Do Until isOk    ' 条件を満たすまで繰り返し
       isOk = check(hoge)
    Loop

繰り返し文の途中で抜ける

  • For文
    For i = 0 To 4
        If 条件 Then
            Exit For    ' 条件を満たす場合、For文を抜ける。
        End If
    Loop
  • Do While文・Do Until文
    i = 0
    Do While i < 5
        If 条件 Then
            Exit Do    ' 条件を満たす場合、Do While文を抜ける。
        End If
    Loop

Collectionのループ

Count で要素数を取得できるので、それで For ループを回すことができる。
もしくは、 For Each でループすることもできる。

Dim list As New Collection
list.Add "hoge"
list.Add "fuga"
list.Add "piyo"
' Count で要素数を取得してループ
Dim i As Integer
For i = 1 To list.Count
    Debug.Print (i & " : " & list(i))
Next
' For Eachでループ
Dim e As Variant
For Each e In list
    Debug.Print e
Next
  • 実行結果
    1 : hoge
    2 : fuga
    3 : piyo
    hoge
    fuga
    piyo

Dictionaryのループ

Dim Map As New Dictionary
Map("hoge") = "Hoge"
Map.Add "fuga", "Fuga"
Dim Key As Variant
For Each Key In Map
    Debug.Print "Key=" & Key & ", Value=" & Map(Key)
Next
  • 実行結果
    Key=hoge, Value=Hoge
    Key=fuga, Value=Fuga

TIPS

別ページの一覧を入れる。

'IT系/VBA/基本/繰り返し処理/' には、下位層のページがありません。

リンク集

重複を恐れないリンク集。

動画

その他メモ