在For循环中复制行并粘贴到新工作表

我有问题根据条件复制/粘贴行。

Dim lastrow1 As Long Dim lastcolumn1 As Long Dim Distance As Long Distance = 14 Set sh = ThisWorkbook.Sheets("Sample Address Database") Set sh2 = ThisWorkbook.Sheets("Workspace") lastrow1 = sh.Cells(Rows.Count, "A").End(xlUp).row lastcolumn1 = sh.Cells(1, Columns.Count).End(xlToLeft).Column Dim L As Long For L = 2 To lastrow1 If _ sh.Cells(L, Distance).Value <= CDbl(cboRadius.Value) Then sh.Range("A" & L & ":" & lastcolumn1 & L).Copy _ Destination:=sh2.Range("A" & L) End If Next 

cboRadius.Value是一个用户表单中的数字(这一行没有问题)

每当我尝试运行这个代码,我得到一个“运行时错误'1004':对象'_Worksheet'的方法'范围'失败,黄色的箭头指向目标线。什么问题?

编辑: Ed Heywood-Lonsdalebuild议我改变

 sh.Range("A" & L & ":" & lastcolumn1 & L).Copy _ 

 sh.Range("A" & L & ":A" & lastcolumn1 & L).Copy _ 

现在只有列A,或者如果我将其更改为B,C,D等正在被复制。 我认为问题在于它可能没有logginglastcolumn1和L是列/行号,而是使它们成为一个值,从而导致范围故障。

我只是使用内置的Excelfilter来过滤数据,然后复制结果而不是尝试循环遍历每一行。

但是如果你想循环行:

为了使用Rangefunction,您需要使用列号而不是列号。

你有2个选项。 使用

 Chr(lastcolumn1 + 64) 

而不是lastcolumn1。 缺陷是这只适用于列Z到列,并且它不适用于没有if语句和更多代码的双字母列。 像以下应该工作到ZZZ

 If lastcolumn1> 52 Then strColumnLetter = Chr(Int((lastcolumn1- 1) / 52) + 64) & Chr(Int((lastcolumn1- 27) / 26) + 64) & Chr(Int((lastcolumn1- 27) Mod 26) + 65) ElseIf lastcolumn1> 26 Then strColumnLetter = Chr(Int((lastcolumn1- 1) / 26) + 64) & Chr(Int((lastcolumn1- 1) Mod 26) + 65) Else strColumnLetter = Chr(lastcolumn1+ 64) End If 

但你也可以使用

 strColumnLetter = Split(Cells(1, lastcolumn1).EntireColumn.Address(False, False), ":")(0) 

要么

 strColumnLetter = Left(Replace(Cells(1, lastcolumn1).Address(1, 0), "$", ""), InStr(1, Replace(Cells(1, lastcolumn1).Address(1, 0), "$", ""), 1) - 1) 

要么

 strColumnLetter = Left(Cells(1, lastcolumn1).Address(1, 0), InStr(1, Cells(1, lastcolumn1).Address(1, 0), "$") - 1) 

因为这将适用于Excel所能容纳的列数。

如果不想将数字转换为列字母,则最后一个选项是获取一系列单元格,因为Cells函数CAN可以接受参数的列号。

 sh.Range(cells(L,1), cells(L,lastcolumn1)) 

再次,我会build议使用标准的内置过滤function来过滤掉你不想要的数据,然后只是复制剩下的东西。 这只是添加更多的选项。

如果你提供一些样本信息,我可以给你写一个子filter复制粘贴,但我不知道你的数据是如何设置的。

这里是一个应该根据你原来的问题工作的例子:

 Sub FilterAndCopy() Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlCalculationManual Dim sh As Worksheet, sh2 As Worksheet Dim lastrow1 As Long Dim lastcolumn1 As Long Dim Distance As Long Distance = 14 Set sh = ThisWorkbook.Sheets("Sample Address Database") Set sh2 = ThisWorkbook.Sheets("Workspace") lastrow1 = sh.Cells(Rows.Count, "A").End(xlUp).Row lastcolumn1 = sh.Cells(1, Columns.Count).End(xlToLeft).Column With sh .Range(.Cells(1, 1), .Cells(lastrow1, lastcolumn1)).AutoFilter , _ field:=Distance, _ Criteria1:="<=" & CDbl(151), _ Operator:=xlAnd .Range(.Cells(2, 1), .Cells(lastrow1, lastcolumn1)).Copy _ sh2.Range("A2") End With Application.ScreenUpdating = True Application.EnableEvents = True Application.Calculation = xlCalculationAutomatic End Sub 

定义要复制的范围时,尝试添加“A”:

 sh.Range("A" & L & ":" & lastcolumn1 & L) 

 sh.Range("A" & L & ":A" & lastcolumn1 & L)