匹配两个数组并返回匹配单元格的地址,然后复制该单元格的下一列

时间:2014-12-01 08:14:19

标签: excel vba excel-vba

在一个工作表中,

  • 我在A列中的值为1到10,它们由三个空行分隔,表示A1中的value1,A4中的value2,依此类推。
  • 在B列中,我有数字,但是按随机顺序但是它们在A列的范围限制内,这意味着如果A列中的最大值是15,B范围内的任何值都不会超过15,并且值B中的值与A的值相同。
  • 在C栏中,我有B范围内每个数字的值,我有4个答案。所以对于B1中的第一个值,我有C1,C2,C3,C4等。

现在我要做的是:我希望将B列中的值与A匹配,然后复制C的四个值,然后粘贴到D中找到匹配值。

例如,如果我在列B中有5作为第一个值,我想检查该值在A列中的位置,然后复制C1,C2,C3,C4并将它们粘贴在A列中的5前面 我想用Arrays做到这一点。

我已经使用循环和匹配函数编写了一个宏,但它不是很实用,因为我有很多文件需要循环并且有很长的A和B列所以它需要时间并且还有许多其他限制,< strong>那么有没有另一种方法来实现这个目标,例如使用数组?如果我为范围A和范围B使用了两个数组,我如何使用匹配函数或锁定来比较它们?这是我的宏:

Dim see As Worksheet
Set see = ThisWorkbook.Sheets("Sheet2")
Dim rega As Range
Dim numb As Long
Dim tr As Integer
Dim dd As Long
With see
    Set rega = .Range(.Cells(3, gh + 2).Address, .Cells(23, gh + 2).Address)
End With
For tr = 3 To 40 Step 4
    numb = M.Application.WorksheetFunction.Match(see.Cells(tr, 1 + gh), rega, 0)
    For dd = 0 To 3
        see.Cells(numb + dd, gh + 3).Copy
        see.Cells(te + dd, gh + 4).PasteSpecial
    Next dd
Next

1 个答案:

答案 0 :(得分:0)

您可以删除至少一个循环并将复制,粘贴特殊转换为直接值传输。

With see
    Set rega = .Range(.Cells(3, gh + 2).Address, .Cells(23, gh + 2).Address)
    For tr = 3 To 40 Step 4
        numb = M.Application.Match(.Cells(tr, 1 + gh), rega, 0)
        .Cells(tr, gh + 4).resize(4, 1) = .Cells(numb, gh + 3).resize(4, 1).value
    Next tr
End With

......代替,

With see
    Set rega = .Range(.Cells(3, gh + 2).Address, .Cells(23, gh + 2).Address)
End With
For tr = 3 To 40 Step 4
    numb = M.Application.WorksheetFunction.Match(see.Cells(tr, 1 + gh), rega, 0)
    For dd = 0 To 3
        see.Cells(numb + dd, gh + 3).Copy
        see.Cells(te + dd, gh + 4).PasteSpecial
    Next dd
Next

(我假设拼写错误并将see.Cells(te, gh + 4)更改为see.Cells(tr, gh + 4)

除此之外,除了关闭事件,计算和屏幕更新之外,我没有太多建议。

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

' run all the code

Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True