I have worksheets I want to copy to a new, temporary workbook -- without saving it.
Worksheet.Copy
copies the worksheet to a new, unnamed'ish (Book1, Book2, Book3, etc) workbook. I want all sheets to be copied to the same workbook.
For all worksheets after the first, I have tried using Worksheet.Copy After:=xlWb.Sheets(1)
, but I do not know how to reference the newly created workbook when setting the xlWb workbook-object. I keep receiving
run-time error 9, 'Subscript out of range'.
Dim xlApp As Excel.Application
Dim xlWb As Excel.Workbook
Dim xlWbOld As String
Dim xlWs As Excel.Worksheet
Dim xlWbNew As Excel.Workbook
Dim xlWsOld As Excel.Worksheet
Dim xlRng As Excel.Range
Dim xlRngOld As Excel.Range
xlWbOld = ActiveWorkbook.Name
Set xlApp = New Excel.Application
xlApp.Visible = True '*** Quite Important to set Excel.Visible,_
'Otherwise user wouldn't see the application's running _
'even though it would run as background
xlApp.Application.ScreenUpdating = False
Set xlWb = xlApp.Workbooks.Add 'Create a new Workbook
Set xlWs = xlWb.Worksheets.Add
And this is where the worksheets should be copied:
Select Case strRptType
Case "DAILY"
xlWs.Name = "1-Daily Price"
'Check the last column and the last row
lLastRow = oBasic.GetLast(, "DailyRpt", False, "A")
iLastCol = oBasic.GetLast(, "DailyRpt", True, 4)
Set xlRngOld = wksDailyRpt.Range(wksDailyRpt.Cells(4, 1), wksDailyRpt.Cells(lLastRow, iLastCol))
Application.ScreenUpdating = True
xlRngOld.Copy
Set xlRng = xlWs.Cells(1, 1)
xlRng.PasteSpecial Paste:=xlPasteValues
xlWs.Columns.AutoFit
For Each xlWsOld In ActiveWorkbook.Worksheets
If xlWsOld.Name = "ForwardPrices" Or xlWsOld.Name = "ForwardVolatilities" _
Or xlWsOld.Name = "ForwardReturns" Or xlWsOld.Name = "ForwardCorrelations" Then
Sheets(xlWsOld.Name).Copy After:=Workbooks(xlWb).Sheets(1)
End If
Next xlWsOld
End Select
Workbooks
collection members to obtain newly created workbook name. – Peter L.Sheets(xlWsOld.Name).Copy After:=Workbooks(xlWb).Sheets(1)
toxlWsOld.Copy After:=xlWb.Sheets(1)
- sorry, don't have time right now to investigate further. – chris neilsen