我有一些代码wb
是现有的多工作表工作簿。如果我复制其中一个“概述”工作表,则会创建一个新工作簿 - 为什么以下错误说“需要对象”?:
Dim wbCopy As Excel.Workbook
Set wbCopy = wb.Sheets("Overview").Copy
答案 0 :(得分:8)
Worksheet.Copy
方法不会返回对新工作簿的引用。您可以改为使用Worksheet引用:
Dim wsCopy As Excel.Worksheet 'changed from wb to wsCopy
如您所知,如果您未提供After或Before参数,则会将其复制到新的工作簿。在同一工作簿中复制将使用此代码:
Set wsCopy = wb.Worksheets("Overview")
wsCopy.Copy After:= wb.Worksheets(1) 'or Before:=
如果要将工作表复制到新工作簿并保留对它的引用,则需要分阶段完成:
Dim wbNew As Excel.Workbook
Dim wsCopied As Excel.Worksheet
Set wbNew = Workbooks.Add
wsCopy.Copy before:=wbNew.Worksheets(1)
Set wsCopied = wbNew.Worksheets(1)
如果您只需要保留对新工作簿的引用,那么只需省略最后一行(以及wsCopied的变量声明)。
答案 1 :(得分:6)
这是您必须使用其中一个Active*
对象
wb.Sheets("Overview").Copy
Set wbCopy = ActiveWorkbook
答案 2 :(得分:3)
工作表复制方法似乎返回布尔值而不是工作簿对象。要设置对工作簿的引用,可以使用以下命令。
Sub wbcopy()
Dim wbcopy As Excel.Workbook
Dim wbIndex As Excel.Workbook
Dim sArray() As String
Dim iIndex As Integer
Dim bfound As Boolean
Dim wb As Workbook
Set wb = ThisWorkbook
ReDim sArray(Workbooks.Count)
'Find the names of all the current workbooks
For Each wbIndex In Workbooks
sArray(iIndex) = wbIndex.FullName
Next wbIndex
'Copy the sheet to a new workbook
wb.Sheets("Overview").Copy
'Find the sheet with the new name
For Each wbIndex In Workbooks
bfound = False
For iIndex = LBound(sArray) To UBound(sArray)
If wbIndex.FullName = sArray(iIndex) Then
bfound = True
Exit For
End If
Next iIndex
If Not bfound Then
Set wbcopy = wbIndex
Exit For
End If
Next wbIndex
End Sub
答案 3 :(得分:0)
dim sws, tws as worksheet
set sws = thisworkbook.sheets("source")
sws.copy before:=sws
set tws = sws.previous
这就是工作
rn43x