我发现这段代码在工作表中搜索H列,并在新工作簿中复制包含单词“apply”的单元格。 然后我尝试更改它以便复制整行,但无法弄清楚我做错了什么,因为它现在只是打开一个新的工作簿并将其留空。 有人可以看看代码并告诉我我做错了什么吗? 非常感谢
Sub test()
Dim K, X As Long, r As Range, v As Variant
K = 1
X = 5
Dim w1 As Workbook, w2 As Workbook
Set w1 = ThisWorkbook
Set w2 = Workbooks.Add
w1.Activate
For Each r In Intersect(Range("H:H"), ActiveSheet.UsedRange)
v = r.Value
X = X + 1
If InStr(v, "applied") > 0 Then
'**Initial line** - r.Copy w2.Sheets("Sheet1").Cells(K, 1)
With w2
w1.Sheets("Sheet1").Rows("X:X").Copy .Sheets("Sheet1").Rows("K")
K = K + 1
End With
End If
Next r
End Sub
答案 0 :(得分:0)
您的代码中存在多个错误。
您正在使用字符串进行行引用。 " X:X"将解析为字符串X:X。它不会替换字符串中的X值。同样适用于" K"在表2上。
您正在复制您找到"已应用"行的第五行。
如果你想复制同一行,我建议:
Dim K, X As Long, r As Range, v As Variant
K = 1
Dim w1 As Workbook, w2 As Workbook
Set w1 = ThisWorkbook
Set w2 = Workbooks.Add
w1.Activate
For Each r In Intersect(Range("H:H"), ActiveSheet.UsedRange)
v = r.Value
X = X + 1
If InStr(v, "applied") > 0 Then
r.EntireRow.Copy w2.Sheets("Sheet1").Rows(K)
K = K + 1
End If
Next r
您也可以将复制行更改为:
r.EntireRow.Copy w2.Sheets("Sheet1").Cells(K, 1)
但我不知道这个是否比另一个更有效。