【问题标题】:Copy an entire row from 1 worksheet to another将整行从一个工作表复制到另一个
【发布时间】:2015-11-13 09:36:30
【问题描述】:

我在下面发送了一些代码,但无法让它工作。

Sub mybus()
    Dim x As Long

    x = 2

    'start the loop
    Do While Cells(x, 1) <> ""
        'look for data with "bus"
        If Cells(x, 1).Value = "bus" Then
            'copy the entire row if it contains bus
            Workbooks("book1").Worksheets("Sheet1").Rows(x).Copy
            'Go to sheet 2 activate it, we want the data here
            Workbooks("book1").Worksheets("Sheet2").Activate
            'Find the first empty row in sheet2
            erow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
            'paste the data here
            ActiveSheet.Paste Destination:=Worksheets("sheet2").Rows(erow)
        End If
        'go to sheet1 again and activate it
        Worksheets("Sheet1").Activate
        x = x + 1

    Loop
End Sub

【问题讨论】:

标签: vba excel


【解决方案1】:

避免同时使用Range .Activate methodWorksheet.Activate method。您只需要指定多单元格粘贴中的第一个单元格。

Sub mybus()
    Dim x As Long, erow As Long

    x = 2

    With Workbooks("book1").Worksheets("Sheet2")
        erow = .Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    End With

    With Workbooks("book1").Worksheets("Sheet1")
        Do While Cells(x, 1) <> ""
            'look for data with "bus"
            If Cells(x, 1).Value = "bus" Then
                'copy the entire row if it contains bus to Sheet2's erow
                .Rows(x).Copy _
                   Destination:=.Parent.Worksheets("sheet2").Cells(erow, 1)
                'sequence erow to a new blank row
                erow = erow + 1
            End If
            x = x + 1
        Loop
    End With

End Sub

请参阅How to avoid using Select in Excel VBA macros,了解更多摆脱依赖选择和激活来实现目标的方法。

【讨论】:

  • 我很接近 =P 我知道这与增加 erow 有关。编辑:我很惊讶你一直复制/粘贴。为什么不将行设置为行?这不是更快吗?
  • 您永远不知道什么时候带上格式是必不可少的,而 .Value 传输不会那样做。如果 OP 使用副本,那么我坚持使用它;如果它是复制、选择性粘贴、值,那么我将转到值转移。
  • 教我像你一样~
  • 最近,我一直在玩erow = Sheet2.Cells(Rows.Count, 1).End(xlUp)(2).Row,这似乎在获得下一个空白行时给出了一致的结果。将代码缩短一点,但您可能需要在一百个问题中解释一百次。
  • 你能给我解释一下吗=P 我明白了,直到 (2).row。在此之前,你得到了最后一行,那么 2 在做什么?
猜你喜欢
  • 2012-08-28
  • 1970-01-01
  • 2020-08-14
  • 2014-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 2016-10-12
相关资源
最近更新 更多