
次のデータに対して「;」を区切り文字として使用して、テキストを列に分割する機能を使用している場合:
foo;bar;qux;baz;トースト;
quux;ジャム;豆;
結果として得られるセルのグリッドでは、結果が「左揃え」になります。
|foo |bar |qux |baz |toast |
|quux |jam |beans | | |
ただし、それらを「右揃え」にしたいのです。
|foo |bar |qux |baz |toast |
| | |quux |jam |beans |
これどうやってするの?
注記:「右揃え」は正しい用語ではないかもしれないが、
| foo| bar| qux| baz| toast|
| quux| jam| beans| | |
しかし、これは私が求めているものではありません。したがって、私が説明している内容に対して、より適切な用語を提案できる方がいらっしゃいましたら、ぜひ提案してください。
補遺:代替アプローチとして、Excelを使用してセルを並べ替える方法を知っている人がいたら、
|a |b |c |d | | | | | |
|n |m |o |p |q | | | | |
|e |f |g |h |i |j |k |l | |
|n |m |o |p |q | | | | |
|x | | | | | | | | |
なる
| | | | | |a |b |c |d |
| | | | |n |m |o |p |q |
| |e |f |g |h |i |j |k |l |
| | | | |n |m |o |p |q |
| | | | | | | | |x |
それならそれもうまくいくでしょう。
答え1
次の数式を使用すると、データを、Text-to-Columns が記述どおりに右揃えで簡単に解析できる形式にすばやく変換できます。
D5
式(ない場合はセミコロンを追加します):
=IF(RIGHT(B5,1)<>";",B5&";",B5)
G5
式(必要な数のセミコロンを先頭に付加します):
=REPT(";",5-(LEN(D5)-LEN(SUBSTITUTE(D5,";",""))))&D5
結果をコピーし、その後に「値として貼り付け」を実行すると、テキストから列への変換に適した生の素材が得られます。
解決策は、列の最大数が固定されていること(ここでは 5)に依存します。 の式は、G5
シート上の別の場所に「生成する列の数」セルを追加し、ハードコードされた5
値の代わりにこの新しいセルを参照することで一般化できます。
さらに、データの末尾に常にセミコロンが付くことが保証されている場合、 の中間ステップはD5:D7
不要です。
編集:Some_Guyのコメントによると、この方法はすべての行が次のように構築されている場合にも機能します。足らない末尾のセミコロン。
答え2
前述のとおり、これはテキストを列に並べる標準的な機能ではありません。または、私が知る限り、Excel でこれを行う固有の方法があるのでしょうか。ただし、この VBA はそれを実行します (入力されたセルの間に空白がないと仮定します)-
Sub test()
Dim lrow As Integer
lrow = Cells(Rows.Count, "A").End(xlUp).Row
Dim lcol As Integer
lcol = Cells("1", Columns.Count).End(xlToLeft).Column
Dim lfcol As Integer
Dim dif As Integer
For i = 1 To lrow
lfcol = Cells(i, Columns.Count).End(xlToLeft).Column
dif = lcol - lfcol
For j = lfcol To 1 Step -1
If dif = 0 Then Exit For
If Not Cells(i, j) Is Nothing Then
Cells(i, j + dif) = Cells(i, j)
Cells(i, j) = vbNullString
End If
Next
Next
End Sub
答え3
これを実行するための別の VBA ルーチンを次に示します。テキストを列に分割し、データを配置する長方形の範囲 (つまり、列A
- (最大フィールド) × 行) を選択して、このマクロを実行します。MS Office に VBA を追加するにはどうすればよいですか?
教材用。
Sub Copy_Right()
For Each rr In Selection.Rows
For cn = Selection.Columns.Count To 1 Step -1
If Len(rr.Cells(1, cn)) > 0 Then Exit For
Next cn
' cn is now the (relative) column number of the last cell in this row
' that contains (non-blank) data.
my_offset = Selection.Columns.Count - cn
' my_offset is how many columns to the right we need to move.
' If my_offset = 0, the row is full of data (or, at least,
' the last column contains data; there may be blank cells
' to its left), so there’s nowhere to move it.
' If cn = 0, the row is empty, so there’s nothing to move.
If cn = 0 Or my_offset = 0 Then
' Nothing to do.
Else
For cn = Selection.Columns.Count To 1 Step -1
If cn > my_offset Then
' Copy data to the right.
rr.Cells(1, cn) = rr.Cells(1, cn - my_offset)
Else
' Set the cells on the left to blank.
rr.Cells(1, cn) = ""
End If
Next cn
End If
Next rr
End Sub
これ意思埋め込まれた空白セル (例: the;quick;;fox;
) を正しく処理します。それ以外の場合、この回答と他の回答の違いは単なる個人的な好みであり、他の回答の方が私が理解できない点で優れている可能性があります。