如果声明复制单元格,如果它们不为空,则不要复制

If statement to copy cells if they are NOT blank else, don't copy

我只想问我应该如何编写一个 if 语句,如果它们不为空,则将数据复制并粘贴到一系列单元格上,并且如果该特定单元格范围为空,则不应复制任何内容.

非常感谢任何建议。 谢谢!

如果单元格不为空,这会将单元格值从第 1 列 (UsedRange) 复制到第 2 列:


Option Explicit

Public Sub copyIfNotEmpty()

    Dim cel As Range, lRow As Long

    'next line determines the last row in column 1 (A), of the first Worksheet
    lRow = Worksheets(1).UsedRange.Columns(1).Rows.Count

    'iterate over every cell in the UsedRange of column A
    For Each cel In Worksheets(1).Range("A1:A" & lRow)

        'cel represents the current cell
        'being processed in this iteration of the loop

        'Len() determines number of characters in the cell
        If Len(cel.Value2) > 0 Then

            'if cel is not empty, copy the value to the cell next to it

            'cel.Offset(0, 1): cell that is offset from current cell
            ' - 0 rows from current cell's row (1 would be row below, -1 row above)
            ' - 1 column to the right of current cell's column (-1 is column to its left)

            cel.Offset(0, 1).Value2 = cel.Value2

        End If

    Next    'move on the next (lower) cell in column 1

End Sub

在此处查看示例视频,我提供了 2 个示例,一个循环和一个过滤器。 https://youtu.be/a8QJ9BAHlhE

sample workbook.

Sub LoopExample()
    Dim Rws As Long, rng As Range, c As Range

    Rws = Cells(Rows.Count, "A").End(xlUp).Row
    Set rng = Range(Cells(2, "A"), Cells(Rws, "A"))

    For Each c In rng.Cells
        If c <> "" Then
            c.Copy Cells(Rows.Count, "C").End(xlUp).Offset(1, 0)
        End If
    Next c
End Sub
Sub FilterExample()
    Dim Rws As Long, rng As Range

    Rws = Cells(Rows.Count, "A").End(xlUp).Row

    Columns("A:A").AutoFilter Field:=1, Criteria1:="<>"
    Set rng = Range(Cells(2, "A"), Cells(Rws, "A"))
    rng.Copy Range("D2")
    ActiveSheet.AutoFilterMode = 0
End Sub