excel - 使用循环和 if 条件将数据复制并粘贴到另一个工作表
问题描述
以下代码似乎运行顺利,但没有任何内容复制到所需页面
Sub a2()
Sheets.Add.Name = "25 degree"
Sheets("25 degree").Move after:=Sheets("data")
Dim x As Long
For x = 2 To 33281
If Cells(x, 1).Value = 25 Then
Cells("x,1:x,2:x,3:x,4:x,5:x,6").Copy
Worksheets("25 degree").Select
ActiveSheet.Paste
End If
Next x
End Sub
解决方案
我强烈建议不要使用.Select
或根据如何避免在 Excel VBA 中使用 SelectActiveSheet
为每个对象指定工作表。Cells()
Option Explicit
Public Sub DoSomeCoypExample()
Dim wsSource As Worksheet
Set wsSource = ThisWorkbook.ActiveSheet
'better define by name
'Set wsSource = ThisWorkbook.Worksheets("source sheet")
Dim wsDestination As Worksheet
Set wsDestination = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets("data")) 'add at the correct position and set it to a variable
wsDestination.Name = "25 degree" 'so you can use the variable to access the new added worksheet.
Dim iRow As Long
For iRow = 2 To 33281 'don't use fixed end numbers (see below if you meant to loop until the last used row)
If wsSource.Cells(iRow, 1).Value = 25 Then
With wsSource
.Range(.Cells(iRow, 1), .Cells(iRow, 6)).Copy Destination:=wsDestination.Range("A1")
'this line will copy columns 1 to 6 of the current row
'note you need to specify the range where you want to paste
'if this should be dynamic see below.
End With
End If
Next iRow
End Sub
如果你想循环直到最后使用的行,你可以用类似的东西得到它
Dim LastRow As Long
LastRow = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row 'last used row in column A
如果您想粘贴到目标工作表中的下一个空闲行而不是固定范围Destination:=wsDestination.Range("A1")
,您可以使用与上述相同的技术来查找下一个空闲行:
Dim NextFreeRow As Long
NextFreeRow = wsDestination.Cells(wsDestination.Rows.Count, "A").End(xlUp).Row + 1
因此,您可以在粘贴目标中使用它:
Destination:=wsDestination.Range("A" & NextFreeRow)
推荐阅读
- oop - 用正确的设计模式反击顺序耦合
- php - laravel 在文本框中实时搜索并自动填充到其他文本框
- php - wordpress 插件的问题 - 设置或随机数控件以防止跨站点请求伪造
- autohotkey - 如何为被点击的键和被按住 1000 毫秒的键创建不同的热键
- python - 列表理解并不能消除重复
- python - Windows - 有效地将大量数据打印到终端
- html - R函数到HTML
- kubernetes - Baremetal 中的 Kubernetes Cert-manager 问题:等待 HTTP-01 质询传播:错误的状态代码“403”,预期为“200”
- reactjs - 使用钩子将状态从一个组件传递到另一个(不是子组件)
- regex - 带有正则表达式的版本控制模板以提取 github 标记