VBA セルが空白であるかを判定する

  • 作成日 2021.09.06
  • vba
VBA セルが空白であるかを判定する

VBAで、セルが空白であるかを判定するコードを記述してます。

環境

  • OS windows10 64bit

セルが空白であるかを判定

セルが空白であるかを判定するには、「= “”」で判定します。

適当なボタンを用意して、以下のソースコードを記述します。

Private Sub CommandButton1_Click()
    
    If Cells(1, 1).Value = "" Then
        Cells(1, 2).Value = "空白です"
    End If
    
    If Cells(2, 1).Value = "" Then
        Cells(2, 2).Value = "空白ではありません"
    End If
    
End Sub

実行してみます。

判定されていることが確認できます。

IsEmptyを使用

IsEmptyを使用しても、判定することが可能です。

Private Sub CommandButton1_Click()

    If IsEmpty(Cells(1, 1).Value) Then
        Cells(1, 2).Value = "空白です"
    End If
    
    If Not IsEmpty(Cells(2, 1).Value) Then
        Cells(2, 2).Value = "空白ではありません"
    End If
    
End Sub

Lenを使用

Lenを使用しても、判定することが可能です。

Private Sub CommandButton1_Click()

    If Len(Cells(1, 1).Value) = 0 Then
        Cells(1, 2).Value = "空白です"
    End If
    
    If Len(Cells(2, 1).Value) <> 0 Then
        Cells(2, 2).Value = "空白ではありません"
    End If
    
End Sub

LenBを使用しても、同じ結果が得られます。

Private Sub CommandButton1_Click()

    If LenB(Cells(1, 1).Value) = 0 Then
        Cells(1, 2).Value = "空白です"
    End If
    
    If LenB(Cells(2, 1).Value) <> 0 Then
        Cells(2, 2).Value = "空白ではありません"
    End If
    
End Sub