0

I am trying to paste values from another excel worksheet but my code below keeps returning an error. What am i doing wrong ?

Set tempWB = Application.Workbooks.Open(vrtSelectedItem) 'This OPENS the reference workbook

Sheets("Portfolio Worksheet 8.8").Select 'SELECT  A SHEET if you need to
Range("B16:B30").Select 'select SOME RANGE
Selection.Copy 'COPY SOME RANGE

mainWB.Activate 'activate your main workbook
Sheets("Sheet1").Select 'select target sheet
Range("C20").Select 'select target cell
ActiveSheet.PasteSpecial xlPasteValues 'paste the data from the reference worksheet

tempWB.Save 'save and close the reference workbook
tempWB.Close
0

3 Answers 3

1

No need for any selecting or copy-pasting

Set tempWB = Application.Workbooks.Open(vrtSelectedItem) 

With tempWB.Sheets("Portfolio Worksheet 8.8").Range("B16:B30")

    mainWB.Sheets("Sheet1").Range("C20").Resize(.Rows.Count, _
                                                .Columns.Count).Value = .Value
End With

tempWB.Save 'save and close the reference workbook
tempWB.Close
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this worked after changing the Sheet1 Range to Range("B16:B30")
0

It doesn't look like you have declared your variable 'mainWB' ?

2 Comments

Oh sorry i didn't put the whole code since it would take space code works with just the paste function, when i do paste values it gives me an error
Try: Sheets("Sheet1").Range("C20").PasteSpecial xlPasteValues Application.CutCopyMode = False
0

This below worked, thanks for suggestions, however if i want to copy paste several ranges at the same time. So the code below returns a "Next without for" error. I think this second part of the code in ** is causing the problem

Set tempWB = Application.Workbooks.Open(vrtSelectedItem) 'This OPENS the reference workbook

                ' Sheets("Portfolio Worksheet 8.8").Select 'SELECT  A SHEET if you need to


               With mainWB.Sheets("Sheet1").Range("B16:B30")

                tempWB.Sheets("Sheet5").Range("B16:B30").Resize(.Rows.Count, _
                                           .Columns.Count).Value = .Value
                **With mainWB.Sheets("Sheet1").Range("D16:D30")
                tempWB.Sheets("Sheet5").Range("D16:D30").Resize(.Rows.Count, _
                                           .Columns.Count).Value = .Value**

                End With

                tempWB.Save 'save and close the reference workbook
                tempWB.Close

       Next vrtSelectedItem

    Else 'The user pressed Cancel.
    End If
End With

Set fd = Nothing 'Set the object variable to Nothing.

End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.