循环使用许多搜索字词并匹配另一张表格?

时间:2016-12-20 14:32:35

标签: vba excel-vba loops match excel

我使用第三方收集数据以生成月度报告。在此示例中,来自第三方的数据转储位于名为" Data"并且报告表被称为"月"

表格("数据")这是按细分列出的非结构化数据的数据转储,但细分的顺序与我的报告不符:

enter image description here

表格("月")这是结构化报告表,按照适合报告的细分列出数据。来自'数据'的复制数据工作表将粘贴到列O到S

enter image description here

我正在寻找一个可以搜索"数据"的循环,找到B列中的每个连续单词"月"并粘贴来自" Data"的相关信息。进入"月"。

现在,我有一个有效的长代码,但如果其中一个分段名称发生变化,则很容易被破坏。这是一个小部分,只关注第4部分。

Sub Macro1()

' Macro1 Macro
' For post onto StackOverflow

Dim ws As Worksheet
Dim qb As Worksheet
Dim aCell As Range
Set ws = ThisWorkbook.Sheets("Month")
Set qb = ThisWorkbook.Sheets("Data")



'To find Segment 4
  With ws
   Set aCell = .Columns(2).Find(What:="Segment 4", LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=True, SearchFormat:=False)
  If Not aCell Is Nothing Then
       aCell.Offset(0, 1).Value = qb.Range("B2")
    Else
        MsgBox "Segment 4 Not Found"
    End If

qb.Range("B2:F2").Copy
aCell.Offset(0, 13).Select
ActiveCell.PasteSpecial
End With

End Sub

有没有办法可以在"月"中循环通过B列;并将其与A列中的数据相匹配"数据"无需为每个细分市场撰写搜索结果?

提前感谢您的意见!

1 个答案:

答案 0 :(得分:0)

For Each循环如何通过数据A列:

Sub Macro1()

    ' Macro1 Macro
    ' For post onto StackOverflow

    Dim ws As Worksheet
    Dim qb As Worksheet
    Dim aCell As Range
    Set ws = ThisWorkbook.Sheets("Month")
    Set qb = ThisWorkbook.Sheets("Data")
    qb.Activate

    Dim dataCell As Variant
    For Each dataCell In qb.Range(Cells(2, 1), Cells(qb.Cells(qb.Rows.Count, "A").End(xlUp).Row, 1))
        With ws
            Set aCell = .Columns(2).Find(What:=dataCell.Value, LookIn:=xlValues, _
                     LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                     MatchCase:=True, SearchFormat:=False)
            If Not aCell Is Nothing Then
                Range(aCell.Offset(0, 1), aCell.Offset(0, 5)).Value = Range(dataCell.Offset(0, 1), dataCell.Offset(0, 5)).Value
            Else
                MsgBox dataCell.Value & " Not Found"
            End If
        End With
    Next dataCell
End Sub