Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

excel - VBA - Copy and Paste Table Row to Another Table

I am very new to VBA and I am trying to solve what I think should be a very simple problem (I have a Java/J2EE background)... I am looping through a table and want to copy rows to a table on another worksheet based on some conditional statements. See code below.

Sub closeActionItems()
    Dim i, iLastRow As Integer
    Dim date1 As Date
    Dim oLastRow As ListRow

    date1 = Date
    iLastRow = ActiveSheet.ListObjects("Open_Items").ListRows.Count

    For i = 6 To iLastRow
        If Cells(i, 7).Value <= date1 And Cells(i, 7).Value <> vbNullString Then
            Rows(i).Copy
            Set oLastRow = Worksheets("Closed").ListObject("Closed_Items").ListRows.Add
            'Paste into new row

            Application.CutCopyMode = False
            Rows(i).EntireRow.Delete
        End If
    Next
End Sub

I have tried many different iterations but have been unable to find the correct way to copy the contents of the clipboard to the newly created row.

Any help would be appreciated. Thanks ahead of time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Define srcRow as a Range like so:

Dim srcRow as Range

Then in your loop try doing this:

        Set srcRow = ActiveSheet.ListObjects("Open_Items").ListRows(i).Range
        Set oLastRow = Worksheets("Closed").ListObjects("Closed_Items").ListRows.Add

        srcRow.Copy
        oLastRow.Range.PasteSpecial xlPasteValues

        Application.CutCopyMode = False
        Rows(i).EntireRow.Delete

Notice that you still have a problem in that you are deleting rows as you are trying to loop through them, so you probably want to change your loop so that it starts at the bottom and goes up.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...