如何只将具有来自一个工作表的数据的单元格复制到另一个工作表,而不是在两者之间留下空白

我有一个包含4个工作表的工作表,Sheet4(标题为“缺陷列表”)填充在“B列”中,并根据不同标准填写其他表格中的值。 该列表以“B1”开始并且到“B1155”。 我想只将具有数据的单元格复制到从单元格“B12”开始的Sheet3(标题为“缺陷”)。

例如,如果在单元格B3,B36,B756和B1005中只有Sheet4上的数据,则这些数据将被复制到单元格B12,B13,B14和B15中。

这里是我必须复制数据的代码,但它并没有消除空白。

Sub Copy_Values() Dim i As Long Sheets("Deficiency List").Select iMaxRow = 1155 For iRow = 1 To iMaxRow With Worksheets("Deficiency List").Cells(iRow, 2) ' Check that cell is not empty. If .Value = "" Then 'Nothing in this cell. 'Do nothing. Else ' Copy the cell to the destination Worksheets("Deficiencies").Cells(iRow + 11, 2).Value = .Value End If End With Next iRow End Sub 

  If (Trim$(CStr(.Value)) = "") Then 

如果您不希望输出区域中的行被跳过,

  • 声明一个Longvariables来保存目标行号
  • 初始化它在循环之外到11
  • 在else部分,增加variables,然后用它作为行号而不是irow + 11
 Sub Copy_Values() Dim i As Long, d As Long, shtD, shtDL, tmp Dim iMaxRow As Long, iRow As Long Set shtD = Worksheets("Deficiencies") Set shtDL = Worksheets("Deficiency List") iMaxRow = 1155 d = 12 For iRow = 1 To iMaxRow With shtDL.Cells(iRow, 2) tmp = Trim(.Value) If Len(tmp) > 0 Then shtD.Cells(d, 2).Value = tmp d = d + 1 End If End With Next iRow End Sub