我有一些代码,wb
现有的多工作表工作簿在哪里。如果我复制一张“概述”工作表,则会创建一个新工作簿 - 那么为什么会出现以下错误说“需要对象”?:
Dim wbCopy As Excel.Workbook
Set wbCopy = wb.Sheets("Overview").Copy
该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 的变量声明)。
这是您必须使用其中一个Active*
对象的少数场合之一
wb.Sheets("Overview").Copy
Set wbCopy = ActiveWorkbook
工作表复制方法似乎返回布尔值而不是工作簿对象。要设置对工作簿的引用,您可以使用以下内容。
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
我今天遇到了同样的事情。对我来说 active* 对象太模糊了,所以我寻找一种方法来可靠地确定工作表对象。如果有人在寻找这个,这里是文件:
dim sws, tws as worksheet
set sws = thisworkbook.sheets("source")
sws.copy before:=sws
set tws = sws.previous
那做的工作
rn43x