忽略每个VBA中的空单元格

我有一个问题,我的循环(我去通过在每个工作表中的列和复制他们共同列)在VBA中。 我不想忽略空单元格…任何想法? 贝娄是我的代码

Application.ScreenUpdating = False lastRowMaster = 1 For Each Ws In Sheets(Array("1L", "5L")) lastRow = Ws.Range("A" & Rows.Count).End(xlUp).row Ws.Range("A1:A" & lastRow).Copy Destination:=Worksheets("Podatki plana").Range("A" & lastRowMaster) lastRowMaster = Worksheets("Podatki plana").Range("A" & Rows.Count).End(xlUp).row + 1 Next Application.ScreenUpdating = True MsgBox "Done!" 

我改变了这一行代码:

 Ws.Range("A1:A" & lastRow).Copy Destination:=Worksheets("Podatki plana").Range("A" & lastRowMaster) 

对此:

 Ws.Range("A1:A" & lastRow).SpecialCells(xlCellTypeConstants).Copy Destination:=Worksheets("Podatki plana").Range("A" & lastRowMaster) 

使用.SpecialCells(xlCellTypeConstants)限定符只select在其中具有值的单元格。 您可以将xlCellTypeConstants更改为xlCellTypeFormulas或此MSDN文章中列出的任何选项。

这样做的好处是你不必循环遍历每个单元格,这是一个非常好的解决scheme,但会带来性能损失。

在Excel 2013中testing。

也许只是设置每个目标单元格的原始单元格不是空的时候,像这样

 Application.ScreenUpdating = False lastRowMaster = 1 lastRow = Ws.Range("A" & Rows.Count).End(xlUp).row nextRow = 1 For Each Ws In Sheets(Array("1L", "5L")) for i = 1 to lastRow if Not IsEmpty(Ws.Cells(i, 1)) then Worksheets("Podatkiplana").cells(nextRow, 1) = Ws.cells(i,1) nextRow = nextRow + 1 end if next i Next Application.ScreenUpdating = True MsgBox "Done!" 
 Application.ScreenUpdating = False lastRowMaster = 1 For Each Ws In Sheets(Array("1L", "5L")) lastRow = Ws.Range("A" & Rows.Count).End(xlUp).row For i = 1 to lastrow lastRowMaster = Worksheets("Podatki plana").Range("A" & rows.Count).End(xlUp).row + 1 If ws.cells(i, 1)<> "" Then Worksheets("Podatki plana").Cells(lastRowMaster, 1) = ws.cells(i,1) next i Next Application.ScreenUpdating = True MsgBox "Done!"