如何连接一行中的单元格直到一个特定的值

嗨,我有从地狱这个数据集。 当我得到它的数据会有字段不均匀地跨栏溢出。 所以可能会有一些3列,4列或5列的行

这是数据

ooxyoooxy oo oxo yooy 

清理所需的数据

 oo xy ooo xy oo oxo y ooy 

我试图做的是

  1. 读行直到检测到x
  2. 连接第一列的所有O.
  3. 删除所有其他的O,使x和y可以移动到左边
  4. 有时x可能会被其他文本包装
  5. 有时甚至可能根本就没有一个x。 那么我会跳到下一行,而不是循环无限

我已经search了上下的论坛,但最接近我可以find我的问题是如何连接单元格中的行,直到第一个空白单元格伤心,最后的答案,而不是一个空白单元格是一个具体的价值是不是在那里分享。

我用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 

这里任何帮助都非常值得赞赏

我认为你的数据的最后一行是错误的。

我的数据如下所示:

 ooxyoooxy oo oxo yooyxy oxy 

输出:

 oo xy ooo xy oo oxo y ooy xyoxy 
  1. 扫描整行,直到findx或空白。
  2. 将x之前的所有单元格连接到第一列。
  3. 如果找不到x,则会跳到下一行。

这里是代码:

 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