当第一列中的单元格具有特定文本时,将行复制到新工作表

问题描述 投票:0回答:1

我想只在列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

另外,我没有在我的代码中尝试这个,但如果行之间没有空格则会很好。

谢谢

excel vba copy-paste
1个回答
0
投票

这是我上面编辑的代码,用于处理您的示例数据。运行此工作簿时,请确保包含要从中复制的工作表的工作簿处于活动状态。

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
© www.soinside.com 2019 - 2024. All rights reserved.