Excel VBA サンプルコード解説: 文字列の比較
概要
このサンプルコードは、Excel VBA(Visual Basic for Applications)を使用して、2つの文字列を比較する方法を示しています。具体的には、textA
と textB
の値が等しくない場合にメッセージを表示します。
コード
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
コードの解説
変数の宣言:
Dim textA As String Dim textB As String
textA
とtextB
という2つの文字列型変数を宣言しています。
値の代入:
textA = "Hello" textB = "World"
textA
には文字列 “Hello” を、textB
には文字列 “World” を代入しています。
条件式の評価:
If textA <> textB Then MsgBox "textA is not equal to textB" Else MsgBox "textA is equal to textB" End If
<>
演算子を使用して、textA
とtextB
の値が等しくないかどうかを判定しています。- もし等しくない場合は「textA is not equal to textB」というメッセージが表示されます。
- 等しい場合は「textA is equal to textB」というメッセージが表示されます。
使い方
- Excel ファイルを開きます。
Alt
+F11
キーを押して Visual Basic for Applications エディタを開きます。- 新しいモジュールを挿入し、上記のコードを貼り付けます。
- マクロを実行すると、メッセージボックスが表示されます。
このサンプルコードは、文字列の比較において <>
演算子を使用する方法を理解するのに役立ちます。