簡體   English   中英

Excel VBA:如果單元格值向左= 0,則將單元格文本剪切並粘貼到上方

[英]Excel VBA: Cut & Paste Cell Text to Above, If Cell Value to Left = 0

根據使用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

如果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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM