Excel:如何将包含特定文本的行复制到另一个工作表 (VBA)
Excel: How to copy a row if it contains certain text to another worksheet (VBA)
我希望使用能够在所述 sheet 中搜索列的宏,如果找到特定文本 - 在我的例子中是单词 "FAIL" - 复制整行data/formatting 并将其粘贴到另一个 sheet - sheet 4 在我的例子中 - 以及包含该特定文本的任何其他行。
我一直在使用这段代码,但它只复制粘贴一行然后停止,而不是通过 "FAIL"
复制任何行
Sub Test()
For Each Cell In Sheets(1).Range("H:H")
If Cell.Value = "FAIL" Then
matchRow = Cell.Row
Rows(matchRow & ":" & matchRow).Select
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets(4).Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets(4).Select
End If
Next
End Sub
第一个 post 和 VBA 的全新内容,如果太含糊,请见谅。
这样试试:
Option Explicit
Sub TestMe()
Dim Cell As Range
Dim matchRow As Long
With Worksheets(1)
For Each Cell In .Range("H:H")
If Cell.Value = "FAIL" Then
matchRow = .Cell.Row
.Rows(matchRow & ":" & matchRow).Select
.Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Worksheets(4).Select
Worksheets(4).Rows(matchRow).Select
Worksheets(4).Paste
.Select
End If
Next
End With
End Sub
您的代码中的问题是您没有始终正确引用工作表。因此它不能正常工作。
作为第 2 步,您可以尝试避免在代码中进行所有选择,最好避免在 Excel VBA 中使用 Select 或 Activate .
试试下面的代码(代码内的注释作为注释):
Option Explicit
Sub Test()
Dim Cell As Range
With Sheets(1)
' loop column H untill last cell with value (not entire column)
For Each Cell In .Range("H1:H" & .Cells(.Rows.Count, "H").End(xlUp).Row)
If Cell.Value = "FAIL" Then
' Copy>>Paste in 1-line (no need to use Select)
.Rows(Cell.Row).Copy Destination:=Sheets(4).Rows(Cell.Row)
End If
Next Cell
End With
End Sub
我希望使用能够在所述 sheet 中搜索列的宏,如果找到特定文本 - 在我的例子中是单词 "FAIL" - 复制整行data/formatting 并将其粘贴到另一个 sheet - sheet 4 在我的例子中 - 以及包含该特定文本的任何其他行。
我一直在使用这段代码,但它只复制粘贴一行然后停止,而不是通过 "FAIL"
复制任何行Sub Test()
For Each Cell In Sheets(1).Range("H:H")
If Cell.Value = "FAIL" Then
matchRow = Cell.Row
Rows(matchRow & ":" & matchRow).Select
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets(4).Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets(4).Select
End If
Next
End Sub
第一个 post 和 VBA 的全新内容,如果太含糊,请见谅。
这样试试:
Option Explicit
Sub TestMe()
Dim Cell As Range
Dim matchRow As Long
With Worksheets(1)
For Each Cell In .Range("H:H")
If Cell.Value = "FAIL" Then
matchRow = .Cell.Row
.Rows(matchRow & ":" & matchRow).Select
.Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Worksheets(4).Select
Worksheets(4).Rows(matchRow).Select
Worksheets(4).Paste
.Select
End If
Next
End With
End Sub
您的代码中的问题是您没有始终正确引用工作表。因此它不能正常工作。
作为第 2 步,您可以尝试避免在代码中进行所有选择,最好避免在 Excel VBA 中使用 Select 或 Activate .
试试下面的代码(代码内的注释作为注释):
Option Explicit
Sub Test()
Dim Cell As Range
With Sheets(1)
' loop column H untill last cell with value (not entire column)
For Each Cell In .Range("H1:H" & .Cells(.Rows.Count, "H").End(xlUp).Row)
If Cell.Value = "FAIL" Then
' Copy>>Paste in 1-line (no need to use Select)
.Rows(Cell.Row).Copy Destination:=Sheets(4).Rows(Cell.Row)
End If
Next Cell
End With
End Sub