ExcelVBAでの文字列結合について、構文からプログラミング例まで順に説明していきます。
構文
文字列の結合には、アンパサンド(&)を使用します。アンパサンドは、VBAコード内で文字列同士をつなげる演算子です。
文字列1 & 文字列2
使い方
アンパサンドを使用して、文字列を結合する方法を以下に示します。
Dim str1 As String
Dim str2 As String
Dim str3 As String
str1 = "Hello, "
str2 = "world!"
str3 = str1 & str2
MsgBox str3
Dim str2 As String
Dim str3 As String
str1 = "Hello, "
str2 = "world!"
str3 = str1 & str2
MsgBox str3
上記のコードでは、str1に「Hello, 」、str2に「world!」という文字列を格納しています。そして、str1とstr2をアンパサンドで結合したstr3を作成し、MsgBoxを使用してstr3を表示します。
また、以下のように文字列を直接結合することもできます。
MsgBox "Hello, " & "world!"
プログラミング例
以下は、複数のセルの文字列を結合するプログラムの例です。
Sub ConcatenateCells()
Dim ConcatString As String
Dim Cell As Range
'結合するセルを指定
For Each Cell In Selection
ConcatString = ConcatString & Cell.Value & " "
Next Cell
'結合した文字列を表示
MsgBox ConcatString
End Sub
Dim ConcatString As String
Dim Cell As Range
'結合するセルを指定
For Each Cell In Selection
ConcatString = ConcatString & Cell.Value & " "
Next Cell
'結合した文字列を表示
MsgBox ConcatString
End Sub
このプログラムは、選択したセルの文字列をスペースで区切って結合し、MsgBoxを使用して結合した文字列を表示します。
まとめ
ExcelVBAでは、アンパサンドを使用して文字列を結合することができます。文字列同士をアンパサンドで繋げることで、効率的かつ簡単に文字列を結合することができます。また、複数のセルの文字列を結合することも可能です。