简体   繁体   English

如果单元格包含“,”,如何复制行并将其插入到下面的新行中,并删除原始单元格中“,”之后的内容

[英]How to copy row and insert it in new row below if cell contains “,” and delete what is after the “,” in the original cell

I am trying to copy a row and insert into a new row directly below if a cell in column D contains a ",".如果 D 列中的单元格包含“,”,我正在尝试复制一行并直接插入到下方的新行中。 There is a little more that I want to do, but it is easier to show a sample with before and after of what I want.我想做的还有更多,但更容易展示我想要的之前和之后的样本。

Before

Jon     Junior   Male   A, X    
Pete    Freshman Male   A, X    
Tyler   Senior   Male   A, X, C    
Dave    Senior   Male   A, C, P, U

After

Jon     Junior   Male   A    
Jon     Junior   Male   X    
Pete    Freshman Male   A    
Pete    Freshman Male   X    
Tyler   Senior   Male   A    
Tyler   Senior   Male   X    
Tyler   Senior   Male   C    
Dave    Senior   Male   A    
Dave    Senior   Male   C    
Dave    Senior   Male   P    
Dave    Senior   Male   U

I've tried combining some ideas from past questions, but they don't seem to be working and I haven't really used VBA before.我尝试结合过去问题中的一些想法,但它们似乎不起作用,而且我之前没有真正使用过 VBA。

Dim GCell As Range
Dim N As Long, i As Long
N = ws.Cells(Rows.Count, "D").End(xlUp).Row
For Each GCell In Range("D2:D")
    If GCell.Value Like "*,*" Then
    GCell.Offset(1, 0).EntireRow.Insert
    ws.Cells(i, "D").EntireRow.Copy ws.Cells(i + 1, 1)
    Else

    End If
    i = i + 1
    Next GCell

You can do it thus, adjust sheet names to suit (I put the results on a different sheet):您可以这样做,调整工作表名称以适应(我将结果放在不同的工作表上):

Sub x()

Dim r As Range, v As Variant

For Each r In Sheets("Sheet1").Range("A1").CurrentRegion.Columns(1).Cells
    v = Split(r.Offset(, 3), ",")
    r.Resize(, 3).Copy Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp)(2).Resize(UBound(v) + 1)
    Sheets("Sheet2").Range("D" & Rows.Count).End(xlUp)(2).Resize(UBound(v) + 1).Value = Application.Transpose(v)
Next r

End Sub

Split converts it to an array using a comma as delimiter; Split使用逗号作为分隔符将其转换为数组; by transposing it you turn it into a 'vertical' array which can be pasted in the output sheet.通过转置它,您可以将其变成一个“垂直”数组,可以粘贴在 output 表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM