Excel VBA サンプルコード解説: 文字列の比較

 


Excel VBA サンプルコード解説: 文字列の比較

概要

このサンプルコードは、Excel VBA(Visual Basic for Applications)を使用して、2つの文字列を比較する方法を示しています。具体的には、textAtextB の値が等しくない場合にメッセージを表示します。

コード

Sub CompareStrings()
    Dim textA As String
    Dim textB As String
    
    textA = "Hello"
    textB = "World"
    
    If textA <> textB Then
        MsgBox "textA is not equal to textB"
    Else
        MsgBox "textA is equal to textB"
    End If
End Sub

コードの解説

  1. 変数の宣言:

    Dim textA As String
    Dim textB As String
    
    • textAtextB という2つの文字列型変数を宣言しています。
  2. 値の代入:

    textA = "Hello"
    textB = "World"
    
    • textA には文字列 “Hello” を、textB には文字列 “World” を代入しています。
  3. 条件式の評価:

    If textA <> textB Then
        MsgBox "textA is not equal to textB"
    Else
        MsgBox "textA is equal to textB"
    End If
    
    • <> 演算子を使用して、textAtextB の値が等しくないかどうかを判定しています。
    • もし等しくない場合は「textA is not equal to textB」というメッセージが表示されます。
    • 等しい場合は「textA is equal to textB」というメッセージが表示されます。

使い方

  1. Excel ファイルを開きます。
  2. Alt + F11 キーを押して Visual Basic for Applications エディタを開きます。
  3. 新しいモジュールを挿入し、上記のコードを貼り付けます。
  4. マクロを実行すると、メッセージボックスが表示されます。

このサンプルコードは、文字列の比較において <> 演算子を使用する方法を理解するのに役立ちます。