いつも勉強させていただいております。
表題の件ですが、
エクセルVBAにて、表に入っている文字列をつなげて、変数に入れようとしています。
文字列を繋げる際、文字列と文字列の間には半角スペースを挿入するのですが、
表には空白セルの部分もあり、その場合の処理について悩んでいます。
自分で思いついたのは下記のような方法なのですが、下記以外に効率よく簡潔な方法はないでしょうか?
[方法1]
・変数にセルの値を入れる際に、一緒に半角スペースを入れる
VBA
1Dim max_row As Long 2Dim roop As Long 3 4Dim name_sample As String 5Dim color_sample As String 6Dim type_sample As String 7Dim num_sample As String 8Dim total_sample As String 9 10max_row = Sheets("サンプル").Cells(Rows.Count, "A").End(xlUp).Row 11 12For roop = 2 To max_row 13 name_sample = Sheets("サンプル").Cells(roop, 1) & " " 14 type_sample = Sheets("サンプル").Cells(roop, 2) & " " 15 num_sample = Sheets("サンプル").Cells(roop, 3) & " " 16 color_sample = Sheets("サンプル").Cells(roop, 4) 17 18 total_sample = name_sample & type_sample & num_sample & color_sample 19 20 Sheets("サンプル").Cells(roop, 5) = total_sample 21 22next roop
上記の場合、& " "がついている変数に代入しているセルが空欄の場合、半角スペースから始まってしまったり、半角スペースが連続していまいます。
最終的に置換をかける必要があり、余計なコードが増えてしまいます
[方法2]
・変数の代入を条件で振り分ける
VBA
1Dim max_row As Long 2Dim roop As Long 3 4Dim name_sample As String 5Dim type_sample As String 6Dim num_sample As String 7Dim total_sample As String 8 9 10max_row = Sheets("サンプル").Cells(Rows.Count, "A").End(xlUp).Row 11 12For roop = 2 To max_row 13 if Sheets("サンプル").Cells(roop, 1) <> "" then 14 name_sample = Sheets("サンプル").Cells(roop, 1) & " " 15 else 16 name_sample = "" 17 endif 18 19 if Sheets("サンプル").Cells(roop, 2) <> "" then 20 type_sample = Sheets("サンプル").Cells(roop, 1) & " " 21 else 22 type_sample = "" 23 endif 24 25 if Sheets("サンプル").Cells(roop, 3) <> "" then 26 num_sample = Sheets("サンプル").Cells(roop, 1) & " " 27 else 28 num_sample = "" 29 endif 30 31 color_sample = Sheets("サンプル").Cells(roop, 4) 32 33 34 35 total_sample = name_sample & type_sample & num_sample & color_sample 36 37 Sheets("サンプル").Cells(roop, 4) = total_sample 38 39next roop 40上記の場合、サンプルのように変数が少ないとよいが、変数が10や20と増えた場合にコードが煩雑になり読みにくくなる。 41
このような方法以外で簡潔にわかりやすい考え方がないでしょうか?
初心者で稚拙な質問ですが、よろしくお願いいたします。
VBAだと逆にやりにくいかもだけど、配列に文字列を格納して、最後に展開するときにスペースを入れる、とか。
回答4件
あなたの回答
tips
プレビュー