简体   繁体   English

通过检查条件复制整行并粘贴到不同范围的单元格中

[英]Copy entire row by checking condition and paste into different ranges of cells aside

I am using below code to copy 4 columns of data from range A:D till the end of that row by checking a condition on B column whether its primary or backup.我正在使用下面的代码通过检查 B 列上的条件是主列还是备份,从范围 A:D 复制 4 列数据直到该行的末尾。 If primary category code will paste the data into columns K:N, if backup category paste the entire row to P:S columns.如果主类别代码将数据粘贴到 K:N 列,如果备份类别将整行粘贴到 P:S 列。

But when executing I am getting Object Defined Error.但是在执行时我收到对象定义错误。 Can anybody help with whats wrong in this code ?任何人都可以帮助解决此代码中的问题吗? Thanks谢谢

Public Sub CopyData()


Dim rngSinglecell As Range
Dim rngQuantityCells As Range
Dim intCount As Integer

Range("K2:S1400").Clear

Set rngQuantityCells = Range("B120", Range("B120").End(xlDown))

For Each rngSinglecell In rngQuantityCells

  If rngSinglecell.Value = "Primary" Then

    Range("K" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell.Value,   14).Value = _
        Range(Range("A" & rngSinglecell.Row), Range("D" & rngSinglecell.Row)).Value
  ElseIf rngSinglecell.Value = "Backup" Then

    Range("P" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell.Value, 19).Value = _
        Range(Range("A" & rngSinglecell.Row), Range("D" & rngSinglecell.Row)).Value
  End If
Next

End Sub

Try with Copy :尝试复制:

Public Sub CopyData()


Dim rngSinglecell As Range
Dim rngQuantityCells As Range
Dim intCount As Integer

Range("K2:S1400").Clear

Set rngQuantityCells = Range("B120", Range("B120").End(xlDown))

For Each rngSinglecell In rngQuantityCells

  If rngSinglecell.Value = "Primary" Then

    Range(Range("A" & rngSinglecell.Row), Range("D" & rngSinglecell.Row)).Copy Range("K" & Rows.Count).End(xlUp).Offset(1)

  ElseIf rngSinglecell.Value = "Backup" Then

        Range(Range("A" & rngSinglecell.Row), Range("D" & rngSinglecell.Row)).Copy Range("P" & Rows.Count).End(xlUp).Offset(1)

  End If
Next

End Sub

No need to resize.无需调整大小。

Well, among other things, you're using rngSingleCell.value in two completely different ways, and one of them isn't working.嗯,除此之外,您正在以两种完全不同的方式使用rngSingleCell.value ,其中之一不起作用。

rngSingleCell is the cell that contains Primary/Backup , correct? rngSingleCell是包含Primary/Backup的单元格,对吗? But you're trying to use that value in a resize method, which expects a numeric value.但是您试图在需要数字值的resize方法中使用该值。 This is definitely going to throw you off.这肯定会让你失望。

Of course, without seeing the actual layout of your data it's hard to be sure, but it's not clear why you're using a method a method like Range().end(xlup).offset(1) to define your copying range;当然,如果没有看到数据的实际布局,就很难确定,但不清楚为什么要使用Range().end(xlup).offset(1)来定义复制范围; it's going to keep on copying the same data that way.它将继续以这种方式复制相同的数据。

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

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