在Excel中将多个行从一个工作表复制到另一个工作表的代码

时间:2016-03-29 18:28:43

标签: excel vba excel-vba

首先,感谢阅读和提供的任何帮助。

我在这里基本上一无所知。我花了最近几天试图弄清楚如何编写我想做的事情,我会尽力解释清楚。

我的工作簿有多张,但其中只有两张对此感兴趣:Schedule&移。

在计划表中,有17列和40-100行,其中包含一列中的员工姓名(A列),其首字母(B),员工编号(C),班次(D)和班次(E) - 通过vlookup返回到另一张表。)

基本上,我想要一个按钮,将从这5列中的每一列中的数据复制到从“A3”开始的Shift工作表,并继续复制Schedule中的行,直到它们的名称到达一个空白字段(这是专栏A)。

到目前为止,我已设法使用以下代码复制第一行和第二行:

http://marquetta:8080/birt/frameset?__report=http://marquetta/reports/userList.rptdesign&__format=XLSX

显然,这很笨重,实际上并没有超出我想要的第二次循环。

有任何建议或指示可以帮助我朝着正确的方向前进吗?

再次感谢。

2 个答案:

答案 0 :(得分:0)

你在正确的道路上,你只需要将我们的循环嵌套在另一个循环中。另外,请注意@ BruceWayne的建议。

Private Sub CommandButton1_Click()
    Dim i As Integer
    Dim intCounter As Integer
    Dim IntName As String
    Dim IntInit As String
    Dim IntID As Integer
    Dim Shift As String
    Dim Hours As Integer

    'Adjust intCounter if you want to start on a row other than 1
    intCounter = 1

    Do
        With Worksheets("Schedule")
            IntName = .Cells(intCounter, 1).Value
            IntInit = .Cells(intCounter, 2).Value
            IntID = .Cells(intCounter, 3).Value
            Shift = .Cells(intCounter, 4).Value
            Hours = .Cells(intCounter, 5).Value
        End With

        If IntName = "" Then Exit Do

        i = 1
        Do While i < 5
            'No need to use offset when you can just reference the cell directly.
            'Also, not sure why you select this column anyhow.
            'These lines can probably be deleted?
            'If Worksheets("Shift").Range("a3").Value <> "" Then
            '    Worksheets("Shift").Range("a2").End(xlDown).Select
            'End If

            'Avoid using things like Select, ActiveCell, and ActiveSheet.
            'What if someone clicks on something while your code is running?? Oops!
            With Worksheets("Shift")
                .Cells(i + 1, 2).Value = IntName
                .Cells(i + 1, 3).Value = IntInit
                .Cells(i + 1, 4).Value = IntID
                .Cells(i + 1, 5).Value = Shift
                .Cells(i + 1, 6).Value = Hours
            End With

            i = i + 1
        Loop

        'Increment to go to the next row of Schedule
        intCounter = intCounter + 1
    Loop
End Sub

答案 1 :(得分:0)

蒂姆对紧凑代码的关注带来了这个,试试这个

Private Sub CommandButton1_Click()

With Worksheets("Schedule").Range("A4:E4").CurrentRegion
    .Offset(1).Resize(.Rows.Count - 1).Copy Destination:=Worksheets("Shift").Range("A3")
End With

End Sub