Excel VBA:将单元格文本剪切并粘贴到上方,如果单元格值为左侧= 0

问题描述 投票:0回答:1

根据使用VBA的标题,我正在尝试使用值(非空白)剪切并粘贴(添加逗号)文本值(列C)到上面的第一个单元格,仅在原始单元格的相邻单元格时切割(B列) )是空白的。

为了更简洁地演示,下图(知道总行数是未知值)显示了起点:

    ColumnA ColumnB ColumbC
Row1    a   b   c
Row2            d
Row3    j   k   e
Row4            f
Row5            g
Row6    l   m   h
Row7    n   o   i

以下图表是上述结果之后的结果:

    ColumnA ColumnB ColumbC
Row1    a   b   c, d
Row2            
Row3    j   k   e, f, g
Row4            
Row5            
Row6    l   m   h
Row7    n   o   i
excel vba excel-vba
1个回答
1
投票

如果col A为空,您可以遍历每一行并向上移动信息

Sub test()

    Dim nonEmptyRow As Long: nonEmptyRow = 1
    Dim lastRow As Long
    Dim row As Long

    With ThisWorkbook.Worksheets("insert ur sheet name")
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For row = 1 To lastRow
            If Len(CStr(Trim(.Cells(row, "A").Value))) > 0 Then
                nonEmptyRow = row
            Else
                .Cells(nonEmptyRow, "C").Value = .Cells(nonEmptyRow, "C").Value & ", " & .Cells(row, "C").Value
                .Cells(row, "C").Value = ""
            End If
        Next
    End With

End Sub

反向编辑代码:

Sub test()

    Dim nonEmptyRow As Long
    Dim lastRow As Long
    Dim row As Long

    With ThisWorkbook.Worksheets(1)
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).row
        nonEmptyRow = lastRow

        For row = lastRow To 1 Step -1
            If Len(CStr(Trim(.Cells(row, "A").Value))) > 0 Then
                nonEmptyRow = row
            Else
                .Cells(nonEmptyRow, "C").Value = .Cells(nonEmptyRow, "C").Value & ", " & .Cells(row, "C").Value
                .Cells(row, "C").Value = ""
            End If
        Next
    End With

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.