Why does Worksheet.Copy not return a reference to the new workbook created

前端 未结 4 1465
遥遥无期
遥遥无期 2020-12-19 05:53

I have some code where wb is an existing multi-worksheet workbook. If I copy one of the sheets \"Overview\" a new workbook is created - so why does the followin

4条回答
  •  温柔的废话
    2020-12-19 06:14

    The worksheets copy method appears to return a boolean value rather than a workbook object. To set a reference to the workbook you can use the following.

    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
    

提交回复
热议问题