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
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
看起来您没有声明变量'mainWB'吗?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.