2015-07-05 82 views
0

我只想問如何編寫if語句來複制和粘貼單元格範圍內的數據如果它們不是空的,並且if某些範圍的單元格是空的,那麼它不應該複製任何東西。如果聲明覆制單元格,如果它們不是空白,請不要複製

任何建議都非常感謝。 謝謝!從第1列(UsedRange)

+0

使用宏錄製,以瞭解複製和粘貼,然後換行代碼到'對於Each'環路要檢查所有的細胞,併爲他們每個人,檢查它們的值是否爲空:'如果Range.Value =「」Then ...' – nhee

+0

這與您以前的線程不相似嗎? – Davesexcel

+0

我得到了複製和粘貼的事情,只是不知道用於if語句的語法。無論如何,我需要做的方法是使用循環檢查每個單元格是否空或不正確? – synthaxe

回答

0

該拷貝的細胞的值到第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 
+0

我不想聽起來愚蠢或任何東西,但我有點新vba,如果你可以解釋這段代碼是幹什麼的,那太棒了 – synthaxe

+0

沒問題:我會更新我的回答 –

+0

謝謝隊友!欣賞它的努力 – synthaxe

0

參見示例視頻這裏,我提供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 
相關問題