Copy a cell on one sheet and paste it on another VBA based on cell from each sheet matching

StackOverflow https://stackoverflow.com/questions/22364673

  •  13-06-2023
  •  | 
  •  

Domanda

I am hoping someone can help me out here. I have the below code returning an error message when I run it. I have a report that I import every hour into Sheet2. I need to take the value in cell D16 and copy it. Then I need to match Sheet2!A2 to the cell in Row 1 on Sheet3 and paste the data under the corresponding column.

I would appreciate any input or suggestions to resolve this.

Thanks in advance!

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

È stato utile?

Soluzione

I would do this one:

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

for exact match use res = Application.Match(ws1.Range("A2"), ws2.Range("1:1"), 0)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top