
如果我對以下資料使用“文字分列”功能,請使用“;”作為分隔符號:
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
以下公式將允許您的資料快速轉換為文字到列將輕鬆解析右對齊的形式,如您所描述的:
D5
公式(如果沒有則附加分號):
=IF(RIGHT(B5,1)<>";",B5&";",B5)
G5
公式(前置必要數量的分號):
=REPT(";",5-(LEN(D5)-LEN(SUBSTITUTE(D5,";",""))))&D5
複製結果,然後貼上特殊值作為值應該提供適合文字到列轉換的原材料。
解決方案取決於固定的最大列數;在這裡,五個。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;
)。否則,這個答案與另一個答案之間的差異只是任意的個人偏好,而另一個答案可能在我不理解的方面更優越。