我只想问我应该如何写一个if语句,将数据复制并粘贴到一系列单元格上,如果它们不是空的,如果某个单元格范围是空的,那么它不应该复制任何东西。 / p>
任何建议都非常感谢。 谢谢!
答案 0 :(得分:0)
如果单元格不为空,则将单元格值从第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
答案 1 :(得分:0)
在此处查看示例视频,我提供了2个示例,一个循环和一个过滤器。 https://youtu.be/a8QJ9BAHlhE
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