Excel 2010:从表2复制单元格块> sheet1基于标准

时间:2013-07-30 09:57:40

标签: excel vba excel-vba

早上好......

我正在尝试在excel 2010中执行以下操作:

搜索Sheet1,col A代表'test a'或'test b'等。如果找到'test a',则搜索Sheet 2,col A,查看所有出现的'test a'和copy sheet 2 col从表1中找到的初始“测试a”开始,向表1中的每行输出B-> P,对于表2中的每一行向下递增。

表1:

col A:

  • 测试一个
  • XXXXXX
  • XXXXX
  • XXXX

  • 测试b

  • XXXXXX
  • XXXXX
  • XXXX

  • test c

  • XXXXXX
  • XXXXX
  • XXXX

表2:

Col A,B,C,D, - > Col P

  • 测试a,1,2,3,4 ....
  • 测试a,5,6,7,8 ....
  • 测试a,a,b,c,d ....
  • 测试a,e,f,g,h ....

  • 测试b,1,2,3,4 ....

  • 测试b,5,6,7,8 ....
  • 测试b,a,b,c,d ....
  • 测试b,e,f,g,h ....

期望的结果:

  • 测试a,1,2,3,4 ......
  • xxxxxx,5,6,7,8 ....
  • xxxxx,a,b,c,d ....
  • xxxx,e,f,g,h ....

从未做过任何excel / vb编码,我很难开始!。

我能做的最好的是高级代码:

For search criteria 'test a|test b ..'
 if sheet 1, col A equal to 'criteria' (save row where found)
   if sheet2, col A equal to 'criteria'
     copy sheet2, col b->col p, row (where 'criteria' found) > sheet1, Col B, row (where criteria found in sheet1), incrementing row downwards as we go.

非常感谢有关如何实现这一目标的一些指导!

非常感谢

1 个答案:

答案 0 :(得分:0)

这是一个粗略的草图,可以帮助你入门。使用嵌套循环结构,因此效率不高,但提供基本功能,并允许您自定义以更好地适应您的数据。

Sub SearchCriteria()

Dim ws1 As Worksheet
Set ws1 = Sheet1

Dim ws2 As Worksheet
Set ws2 = Sheet2

Dim ws1RowCounter As Integer
ws1RowCounter = 2

Dim ws2RowCounter As Integer
ws2RowCounter = 2

Dim innerCounter As Integer
innerCounter = 0

Dim ws1Select As String
Dim ws2Select As String

Dim copyRange As Range

Do While ws1.Cells(ws1RowCounter, 1) <> ""

    'look for this value in ws2
    ws1Select = ws1.Cells(ws1RowCounter, 1)

    'loop through ws2 range, look for matches
    Do While ws2.Cells(ws2RowCounter, 1) <> ""
        ws2Select = ws2.Cells(ws2RowCounter, 1)

        If InStr(ws1Select, ws2Select) > 0 Then
            'copy range if match found
            Set copyRange = Range(ws2.Cells(ws2RowCounter, 2), ws2.Cells(ws2RowCounter, 16))
            copyRange.copy
            Set copyRange = Range(ws1.Cells(ws1RowCounter + innerCounter, 2), _
                ws1.Cells(ws1RowCounter + innerCounter, 16))
            copyRange.PasteSpecial xlPasteAll
            innerCounter = innerCounter + 1
        End If

        ws2RowCounter = ws2RowCounter + 1

    Loop

    ws1RowCounter = ws1RowCounter + 1
    ws2RowCounter = 1
    innerCounter = 0
Loop

End Sub