将单元格复制到一张工作表上,然后根据每个工作表匹配的单元格将其粘贴到另一个VBA上

时间:2014-03-12 21:52:32

标签: vba excel-vba copy-paste excel

我希望有人可以帮助我。我有以下代码在运行时返回错误消息。我有一个报告,我每小时导入Sheet2。我需要在单元格D16中取值并复制它。然后我需要将Sheet2!A2与Sheet3上的第1行中的单元格匹配,并将数据粘贴到相应的列下。

如果您有任何意见或建议,我将不胜感激。

提前致谢!

Sub CopyPaste()
Dim ws1 As Worksheet, ws2 As Worksheet, rng As Range, frng As Range

Set ws1 = Worksheets("Sheet2")
Set ws2 = Worksheets("Sheet3")
Set rng = ws1.Range("D16")
Set frng = ws2.Rows(1).Find(What:=Range("Sheet2!A2"), After:=Range("Sheet3!A1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
         , SearchFormat:=False)

rng.Copy
frng.Offset(1, 0).PasteSpecial (xlPasteValues)
Application.CutCopyMode = 0

End Sub

1 个答案:

答案 0 :(得分:0)

我会这样做:

Sub CopyPaste()
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim res

    Set ws1 = Worksheets("Sheet2")
    Set ws2 = Worksheets("Sheet3")

    res = Application.Match("*" & ws1.Range("A2") & "*", ws2.Range("1:1"), 0)

    If IsError(res) Then
        MsgBox "Nothing found"
        Exit Sub
    End If

    ws2.Cells(2, res).Value = ws1.Range("D16").Value
End Sub

完全匹配使用res = Application.Match(ws1.Range("A2"), ws2.Range("1:1"), 0)