[英]Create a new sheet everytime the first cell of a row has a specific value - Excel
[英]Copy a row to new sheet when cell in first column has specific text
我只想在B列中的單元格具有特定值(即字符串)時從sheet1復制行。 我使用了下面的代碼,該代碼似乎復制了行,但只是將空單元格粘貼到新表中。
我認為問題在於它正在尋找一個值,而不是一個字符串(字符串可以是一個值嗎?)。 我是否需要將單元格定義為字符串? 很抱歉,如果這些是愚蠢的問題-編碼新問題。
Sub copy_rows()
Sheets.Add After:=Sheets(1)
Sheets(2).Name = "New"
For Each cell In Sheets(1).Range("B:B")
If cell.Value = "banana" Then
matchRow = cell.Row
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets("New").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
End If
Next
End Sub
這是工作表1的示例:
apple 1 2 1
banana 1 3 5
carrot 1 1 1
banana 1 2 3
這是新表:
banana 1 3 5
banana 1 2 3
另外,我沒有在代碼中嘗試此操作,但是如果行之間沒有空格,那會很好。
謝謝
這是我上面編輯的代碼,可用於處理您的示例數據。 確保包含要復制的工作表的工作簿在運行時處於活動狀態。
Sub copy_rows()
'create the new sheet
Sheets.Add After:=Sheets(1)
Sheets(2).Name = "New"
'get the number of rows you need to check
Dim RowCount As Integer
RowCount = WorksheetFunction.CountA(Sheets(1).Range("A:A"))
'iterate over the rows
For r = 0 To RowCount - 1
this_cell = Sheets(1).Range("A1").Offset(r, 0)
If this_cell = "bananas" Then
'iterate over the columns and copy cells to new sheet
For c = 0 To 3
Sheets(2).Range("A1").Offset(x, c) = Sheets(1).Range("A1").Offset(r, c)
Next c
'counter for the offset to next row in new sheet
x = x + 1
End If
Next r
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.