如果row包含word" Hello"将该列中所有已填充的单元格复制到另一个工作表并将其粘贴到列#34; A"

时间:2017-07-22 13:02:47

标签: excel-vba vba excel

我正在尝试创建一个寻找单词" Hello"在工作表nr.1中的变量行。一旦检测到,它应该复制这个单词下的所有填充单元格,并将其粘贴在第2页的#2; B"栏下的第2页中。 我在这里有几个问题,如何找到包含这个单词的单元格,并将所有填充的单元格复制到该地址下,并将它们粘贴到B列下的另一个单页中。

如果有人在这种练习中给我一些例子,我真的很感激。

With Sheets("GCC1")
        lastrowGCC1 = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

arr1 = Array("K", "P", "Q", "AA")
arr2 = Array("A", "D", "E", "O")
  For i = LBound(arr1) To UBound(arr1)
    With Sheets("Project Parts Requisitioning")
         lastrow = Application.Max(n, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
         .Range(.Cells(n, arr1(i)), .Cells(lastrow, arr1(i))).Copy
         Sheets("GCC1").Range(arr2(i) & lastrowGCC1).PasteSpecial xlPasteValues
    End With
Next
Application.CutCopyMode = False

1 个答案:

答案 0 :(得分:0)

Sub Demo()
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim i As Long
    Dim rng As Range, rng2 As Range
    Dim cellFound As Range

    Set ws1 = ThisWorkbook.Sheets(1)  'change to "GCC1" or use number index
    Set ws2 = ThisWorkbook.Sheets(2)
    Set rng = ws1.Range("A:A") 'range to search
    lastrowGCC1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
    Set rng2 = rng(lastrowGCC1, 1)
    i = 1
        With rng
    Set cellFound = .Find(what:="Hello", After:=rng2, LookIn:=xlValues)
            If Not cellFound Is Nothing Then
                FirstAddress = cellFound.Address
                Do
                    ws2.Cells(i, 2) = ws1.Range(cellFound.Address).Value
                    ws2.Cells(i, 3) = cellFound.Address
                    i = i + 1
                    Set cellFound = .FindNext(cellFound)
                Loop While Not cellFound Is Nothing And cellFound.Address <> FirstAddress
             End If
        End With
End Sub

此函数查找列&#34; A&#34;中的所有单元格地址。在工作表1中使用&#34; Hello&#34;写入,然后在列&#34; B&#34;上写下值列#34; C&#34;来自工作表2。

在工作表(1)中,您有:

+---+-------+
|   |   A   |
+---+-------+
| 1 | Hello |
| 2 | Hello |
| 3 | Hello |
| 4 |       |
| 5 |       |
| 6 |       |
| 7 |       |
| 8 |       |
| 9 | Hello |
+---+-------+

Workheet(2)的输出是:

+---+-------+------+
|   |   B   |  C   |
+---+-------+------+
| 1 | Hello | $A$1 |
| 2 | Hello | $A$2 |
| 3 | Hello | $A$3 |
| 4 | Hello | $A$9 |
+---+-------+------+

ps。:如果您的范围太大,请考虑使用匹配方法和字典,例如:Optimise compare and match method using scripting.dictionary in VBA