简体   繁体   中英

Referencing an open excel workbook

fairly new to VBA in excel and having an issue with trying to reference an already-opened workbook. The code below works well until I get to the line where I try to activate the ProductionBook. I get the "subscript out of range" error here which leads me to believe that the workbook is not being activated. Any ideas on how I can overcome this issue? Thanks in advance.

Sub UpdateSales()

'---Code written in the open workbook defined as ProductionBook

Dim ProductionBook As Workbook 'Master file
Dim sbSolvents As Workbook 'S&P BW-query workbook
Dim path1 As String

'---------Define path directory for S&P workbook-------------
path1 = "C:\Users\scullycs\Desktop\P&O\BW Files\Shipped & Pending\January\ISOP.xlsm"

Set sbSolvents = Workbooks.Open(path1)

With sbSolvents
    Range("j19:j36").Select
    Selection.Copy
End With

Set ProductionBook = Workbooks("Master Production File.xlsm")

With ProductionBook
    Worksheets("S&OP Progress").Range("F11").PasteSpecial (xlPasteValues) 'this is where I get the subscript error
End With

End Sub

Try the code below (in the 3rd line from the bottom, you need to modify "Sheet1" to your sheet in sbSolvents that you want to copy from).

Sub UpdateSales()

'---Code written in the open workbook defined as ProductionBook

Dim ProductionBook As Workbook 'Master file
Dim sbSolvents As Workbook 'S&P BW-query workbook
Dim path1 As String

'---------Define path directory for S&P workbook-------------
path1 = "C:\Users\scullycs\Desktop\P&O\BW Files\Shipped & Pending\January\ISOP.xlsm"

Set sbSolvents = Workbooks.Open(path1)
Set ProductionBook = Workbooks("Master Production File.xlsm")

' modify "Sheet1" in the line below to your sheet name
sbSolvents.Worksheets("Sheet1").Range("J19:J36").Copy
ProductionBook.Worksheets("S&OP Progress").Range("F11").PasteSpecial xlPasteValues

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM