我有工作表我想要复制到一个新的临时工作簿 - 而不保存。
Worksheet.Copy
将工作表复制到一个新的,未命名的(Book1,Book2,Book3等)工作簿。我希望将所有工作表复制到同一工作簿中。
对于第一个之后的所有工作表,我尝试使用Worksheet.Copy After:=xlWb.Sheets(1)
,但在设置xlWb工作簿对象时我不知道如何引用新创建的工作簿。我一直在接受
运行时错误9,'下标超出范围'。
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
这是应该复制工作表的地方:
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
答案 0 :(得分:1)
这个小宏遍历所有打开的工作簿的所有工作表,并在当前工作表之后复制它们。
Sub GatherAllSheets()
Dim Wb As Workbook, Sh As Worksheet
For Each Wb In Workbooks
If Not Wb Is ThisWorkbook Then
For Each Sh In Wb.Worksheets
Sh.Copy after:=ActiveSheet
Next Sh
End If
Next Wb
End Sub
这是你需要的吗? 或者您需要在同一张纸上复制纸张的内容?
答案 1 :(得分:0)
我解决了以下问题:
For Each xlWsOld In ActiveWorkbook.Worksheets
If xlWsOld.Name = "ForwardPrices" Or xlWsOld.Name = "ForwardVolatilities" _
Or xlWsOld.Name = "ForwardReturns" Or xlWsOld.Name = "ForwardCorrelations" Then
Set xlRngOld = Nothing
Set xlWsForwards = xlWb.Worksheets.Add
lLastRow = oBasic.GetLast(, xlWsOld.Name, False, "A")
iLastCol = oBasic.GetLast(, xlWsOld.Name, True, 1)
Set xlRngOld = xlWsOld.Range(xlWsOld.Cells(1, 1), xlWsOld.Cells(lLastRow, iLastCol))
xlWsForwards.Name = xlWsOld.Name
xlRngOld.Copy
Set xlRngForwards = xlWsForwards.Cells(1, 1)
xlRngForwards.PasteSpecial Paste:=xlPasteValues
xlWsForwards.Columns.AutoFit
xlWsForwards.Cells(1, 1).Select
Set xlWsForwards = Nothing
End If
Next xlWsOld
答案 2 :(得分:0)
跳过创建新工作簿,并一次性复制所有工作表。
xlWbOld.Sheets(Array("ForwardPrices", "ForwardVolatilities", "ForwardReturns", "ForwardCorrelations")).Copy
Set xlWb = ActiveWorkbook
这样复制就会创建成为ActiveWorkbook的新工作簿。然后你可以将它分配给工作簿对象,稍后在
上用该名称引用它