excel - 对于每个循环中的 cell.activate:运行时错误“1004”:Range 类的激活方法失败
问题描述
我正在尝试使用以下代码进行 For Each 循环。
Sub child_builder()
Dim cell As Range
For Each cell In ActiveSheet.Range("D5:D102")
If cell.Value = "Y" Then
cell.Activate
Selection.Offset(0, -2).Select
Selection.Copy
Sheets("Child").Select
ActiveSheet.Paste
Selection.Offset(0, 1).Select
ThisWorkbook.Sheets("Product Builder").Activate
Range("G6:I10").Select
Selection.Copy
Sheets("Child").Select
ActiveSheet.Paste
Selection.End(xlDown).Select
Selection.Offset(1, -1).Select
End If
Next cell
End Sub
第一个循环有效,但由于该行而在下一个循环中失败cell.activate
。
错误是
运行时错误“1004”: Range 类的激活方法失败。
解决方案
也许这会让你开始,我知道开始重写宏记录器的东西很难。考虑代码中的注释。
Sub child_builder()
Dim cell As Range
Dim RowToPasteTo As Long
RowToPasteTo = 1
For Each cell In ThisWorkbook.Sheets("PutTheNameOfYourSheetHere").Range("D5:D102")
If cell.Value = "Y" Then
'From the cell that has a Y in it, move left 2 columns and copy that to the A1 cell on the sheet "Child". Also consider just assigning a value with = if you dont need formats etc.
cell.Offset(0, -2).Copy ThisWorkbook.Sheets("Child").Range("A" & RowToPasteTo) 'Change the range here if you wanna paste somewhere else
'I am not sure what you are doing now but I assume you want to copy Range G6:I10 from the "Product Builder" sheet just to the right of the value we just copy pasted?
ThisWorkbook.Sheets("Product Builder").Range("G6:I10").Copy ThisWorkbook.Sheets("Child").Range("B" & RowToPasteTo) 'Change the range here if it needs to go somewhere else.
'From what I can tell you want to paste stuff just below what ever you just pasted on the next loop?
RowToPasteTo = RowToPasteTo + 5 'Move down 5 rows (because G6:I10 are 5 rows)
End If
Next
End Sub
推荐阅读
- swift - 使用 SpriteKit 在 iPhoneX 上的屏幕尺寸问题
- ios - NavigationLink 无法正确加载我的个人视图 (SwiftUI)
- python - 无法通过 setup.py 正确安装我的脚本
- python-3.x - 使用 Google API 客户端默认凭据创建 Blogger API 端点时出错
- javascript - React 路由器未在 Redirect 上加载组件
- python - 从给出重复项运行的序言中的查询
- java - 在 ExpandableListView 中单击 onChildClick 后,如何在没有将 ExpandableListView 附加到新 Activity 的情况下移动到新 Activity
- bash - bash + 将文本文件转换为 csv 文件
- javascript - 我想创建一个函数,将时间与一组 div 类进行比较(如果措辞不正确,编码是新手)
- javascript - 组件在本机反应中未按预期呈现图像