繁体   English   中英

Excel VBA 自动根据单元格值复制整行“X”次并粘贴到单独的工作表中

[英]Excel VBA automation copy entire row “X” times based on cell value and paste in separate sheet

VBA 相对较新,我遇到的情况是我有一个 A 列到 Y 列,我需要根据 O 列中的数值复制和粘贴 X 次。我使用了以下代码,该代码仅适用于复制到单独的工作表中。 我现在遇到的问题是我已经改变了,所以 A 列中有公式,使其更具动态性; 但是,现在代码正在复制公式。

我对 pastespecial 进行了更多研究,但似乎无法让我的代码与下面的第一个代码一样,只是将公式的值粘贴到 A 列中。 我不依赖于复制整行,但我确实需要 AY 列。 非常感谢任何帮助!

Public Sub CopyData()
' This routing will copy rows based on the quantity to a new sheet.
Dim rngSinglecell As Range
Dim rngQuantityCells As Range
Dim intCount As Integer

' Set this for the range where the Quantity column exists. This works only if there are no empty cells
Set rngQuantityCells = Range("D1", Range("D1").End(xlDown))

For Each rngSinglecell In rngQuantityCells
    ' Check if this cell actually contains a number
    If IsNumeric(rngSinglecell.Value) Then
        ' Check if the number is greater than 0
        If rngSinglecell.Value > 0 Then
            ' Copy this row as many times as .value
            For intCount = 1 To rngSinglecell.Value
                ' Copy the row into the next emtpy row in sheet2
                Range(rngSinglecell.Address).EntireRow.Copy Destination:= Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1)                                
                ' The above line finds the next empty row.

            Next
        End If
    End If
Next
End Sub

另外 - 我已经潜伏在这个论坛一段时间了,你们都对自己在这里所做的事情和很棒的资源感到惊讶! 很高兴终于加入。

试试下面的重构代码,这将实现你的目标,而且很可能运行得更快。

Public Sub CopyData()

' This routing will copy rows based on the quantity to a new sheet.
Dim rngSinglecell As Range
Dim rngQuantityCells As Range
Dim intCount As Integer

' Set this for the range where the Quantity column exists. This works only if there are no empty cells
Set rngQuantityCells = Range("D1", Range("D1").End(xlDown))

For Each rngSinglecell In rngQuantityCells

    ' Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell.Value) And rngSingleCell.Value > 0 Then

        ' Copy this row as many rows as .value and 25 columns (because A:Y is 25 columns)
        Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell.Value, 25).Value = _
            Range(Range("A" & rngSinglecell.Row), Range("Y" & rngSinglecell.Row)).Value

    End If
Next

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM