嗨,我有这个来自地狱的数据集。当我得到它的数据时,字段会不均匀地溢出列。所以可能有一些行有3列,4列或5列
这是数据
o o x y
o o o x y
o o oxo y
o o y
清理了所需的数据
oo x y
ooo x y
oo oxo y
o o y
我试图做的是
我在论坛上下搜索,但最接近我能找到的问题是 How to concatenate cells in a row until the first blank cell 遗憾的是,那里没有共享空白单元格而不是特定值的最终答案。
我在VBA中用我粗暴的技巧试试了运气但是......我想我最终会让自己更加困惑他
Sub x()
Dim n As Long, r1 As Range, r2 As Range, v
For n = 1 To Range("A" & Rows.Count).End(xlUp).Row
On Error Resume Next
Rng.SpecialCells(xlCellTypeConstants).Select
If Not r1 = "x" And Not r2 Is Nothing Then
v = Join(Application.Transpose(Application.Transpose(r1)), " ")
Cells(n, 2).Resize(, r1.Count).Clear
r2.Cut Cells(n, 3)
End If
ActiveCell.Offset(1, 0).Select
Next n
End Sub
` 任何帮助都非常值得赞赏
答案 0 :(得分:0)
我认为数据的最后一行输入错误。
我的数据如下:
o o x y
o o o x y
o o oxo y
o o y
x y
o x y
输出:
oo x y
ooo x y
oo oxo y
o o y
x y
o x y
以下是代码:
Sub x()
Dim n, i As Long
Dim r1, r2 As Range
'For concatenating the cells
Dim tmpString As String
'For stopping the while loop
Dim NextLoop As Boolean: Flag = True
For n = 1 To Range("A" & Rows.Count).End(xlUp).Row
'Resetting all variables
tmpString = ""
NextLoop = True
i = 0
On Error Resume Next
'Start scanning the row from column A
Set r1 = Range("A" & n)
'It will stop when a blank cell is detected
Do While r1.Offset(0, i) <> "" And NextLoop
'Check "x" is in the cell or not
If InStr(1, r1.Offset(0, i).Value, "x") > 0 Then
'"x" is found, so stop the loop
NextLoop = False
'Set r2 pointing to the cell with "x"
Set r2 = r1.Offset(0, i)
Else
'"x" is not found yet, so we add the value into tmpString
tmpString = tmpString & r1.Offset(0, i).Value
End If
i = i + 1
Loop
'If NextLoop is true, it means "x" is not found in the row
If Not NextLoop Then
'"x" is found, concancate all cells into the first one
If tmpString <> "" Then r1.Value = tmpString
'If there are cells between r1 and r2, they should be deleted
If r2.Column - r1.Column > 1 Then Range(r1.Offset(0, 1), r2.Offset(0, -1)).Delete xlToLeft
End If
Next n
End Sub