如何复制所有非空单元格并将其粘贴到不同工作表中的下一个可用单元格中

时间:2016-06-16 12:55:53

标签: excel vba excel-vba

我想复制Sheet 1“Delivery Docket”中的值。我要复制的单元格来自A18:A160,所有非空单元格。

下一步是将非空单元格中的值粘贴到Sheet2“Shipping register”上,该单元格将从单元格A2开始,如果单元格不为空,则向下移动。我以前曾要求朋友为我做这个,我依稀记得他添加了一个循环和+ 1函数,因为每当一个单元格有一个值时,宏就必须移动到下一个单元格。

enter image description here

1 个答案:

答案 0 :(得分:0)

试试这个:

Private Sub copyNon_EmptyCells()
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim vals() As String, valCount As Integer
    Dim lastRow As Integer, r As Integer

    Set ws1 = Sheets(1)
    Set ws2 = Sheets(2)

    ' set last row variable
    lastRow = ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Row

    For r = 18 To lastRow
        If (Not ws1.Cells(r, 1) = vbNullString) Then
            ReDim Preserve vals(valCount)
            vals(valCount) = ws1.Cells(r, 1)
            valCount = valCount + 1
        End If
    Next r

    For r = 0 To valCount - 1
        ws2.Cells(r + 2, 2) = vals(r)
    Next r

End Sub