VBA如果存在复制到antoher表中的下一行

时间:2017-04-12 13:54:36

标签: vba

我正在尝试按照我收到的其他工作表值进行排序,并写道:

Sub copy_to_report()

Dim i As Integer
Dim Lastrow As Long

For i = 2 To 500
    If Sheets("Sheet1").Cells(i, 24) <> "" & Sheets("Sheet1").Cells(i, 25) <> "" Then
        Lastrow = Sheets("report").Cells(Rows.Count, 1).End(xlUp).Row
        Sheets("report").Cells(Lastrow, 3) = Cells(i, 24)
        Sheets("report").Cells(Lastrow, 4) = Cells(i, 25)
    End If
Next     
End Sub

然而它不起作用。我想检查连续是否有25和24中的内容,如果是,则将它从sheet1复制到我的“report”表。请你帮助我好吗? :)

1 个答案:

答案 0 :(得分:1)

您的部分Cells不符合相关Worksheet的资格,Lastrow也是如此。

您可以尝试以下代码:

Option Explicit

Sub copy_to_report()

Dim i As Long
Dim Lastrow As Long
Dim ShtReport As Worksheet

Set ShtReport = Worksheets("report")

With Worksheets("Sheet1")
    For i = 2 To 500
        If .Cells(i, 24) <> "" And .Cells(i, 25) <> "" Then
            'Lastrow = ShtReport.Cells(ShtReport.Rows.Count, 1).End(xlUp).Row
            ' maybe it's better to check for last row in Column "C"
            Lastrow = ShtReport.Cells(ShtReport.Rows.Count, "C").End(xlUp).Row
            ShtReport.Cells(Lastrow, 3) = .Cells(i, 24)
            ShtReport.Cells(Lastrow, 4) = .Cells(i, 25)
        End If
    Next
End With

End Sub