« Break a character string in a cell with a comma | トップページ | Break a character string with a comma to make it less than or equal to the specified number of characters »

2018年6月23日 (土)

文字列を任意の文字数以下になるようコンマで改行する

以下の2記事でセル内の文字列を改行する方法を書きました。
セル内の文字列を改行する
セル内の文字列をコンマで改行する

今回はこの2つの記事の方法を合わせたような方法で、
1行が10文字以内になるようにコンマで改行をします。

今までよりは若干コードがわかり難いかもしれませんので、
下記のmacro180609aの説明をしていきます。

改行を追加したい文字列を「Str1」に格納します。
「StrNum」で1行を何文字以内にするのかを指定します。
「Str2」に改行を追加した文字列を作っていきます。

①「Str3」に「Str1」の1文字目から10文字目を格納します。
②この「Str3」で1文字ずつ「,」か「,」と等しいかを判定していきます。
文字列の後ろから調べていって
1文字目からコンマがあった文字までの文字列と改行を
「Str2」に追加します。
③「Str1」を「Str3」で判定したコンマ以降の文字列に変更します。
④この変更した「Str1」を使って
「Str3」に「Str1」の1文字目から10文字目を格納します。
以下②から④の繰り返しです。

最終的に、「Str1」の文字列が11文字より小さく
かつ「Str3」にコンマがなかった場合は
「Str2」に「Str3」をそのまま追加します。

また、最終行でないときに
「Str3」にコンマがなかった場合は
「Str2」に「Str3」と改行を追加します。

コードはこちら

文字列を任意の文字数以下になるようコンマで改行するコード:

Sub macro180623a()
'文字列を改行する
'10文字以内
'半角、全角コンマで区切る

    Dim i As Integer, j As Integer
    Dim StrNum As Integer
    Dim StrLen As Integer
    Dim c As Object
    Dim Str1 As String, Str2 As String, Str3 As String
    Dim Rng As Range
   
    StrNum = 10 '文字数
   
    Set Rng = ActiveSheet.Range("A1:A1") '範囲
   
    For Each c In Rng
        Str1 = c.Text
        StrLen = Len(Str1)
        Str2 = ""
        For i = 1 To StrLen
            Str3 = Mid(Str1, 1, 10)
            For j = Len(Str3) To 1 Step -1
                 If Mid(Str3, j, 1) = "," Or Mid(Str3, j, 1) = "," Then
                     Str2 = Str2 & Mid(Str3, 1, j) & Chr(10)
                    Str1 = Mid(Str1, j + 1, Len(Str1))
                     j = 1
                Else
                    If j = 1 Then
                       '最終行
                        If Len(Str1) < StrNum + 1 Then
                            Str2 = Str2 + Str3
                             i = StrLen + 1
                         Else
                        '最終行でない文字列でコ ンマがない場合
                            Str2 = Str2 + Str3 & Chr(10)
                            Str1 = Mid(Str1, 11, Len(Str1))
                        End If
                    End If
                End If
            Next j
        Next i
        Cells(c.Row, c.Column) = Str2
    Next c
   
End Sub

下の画像の状態で上記のコードを実行
Vba20180623a
実行結果:
Vba20180623b

|

« Break a character string in a cell with a comma | トップページ | Break a character string with a comma to make it less than or equal to the specified number of characters »

コメント

この記事へのコメントは終了しました。

トラックバック


この記事へのトラックバック一覧です: 文字列を任意の文字数以下になるようコンマで改行する:

« Break a character string in a cell with a comma | トップページ | Break a character string with a comma to make it less than or equal to the specified number of characters »