Copy sheet and get resulting sheet object?

后端 未结 13 2131
醉梦人生
醉梦人生 2020-11-28 12:21

Is there any easy/short way to get the worksheet object of the new sheet you get when you copy a worksheet?

ActiveWorkbook.Sheets(\         


        
13条回答
  •  醉梦人生
    2020-11-28 13:12

    As already mentioned here, copy/paste the sheet to the very left (index = 1), then assign it to a variable, then move it where you would like.

    Function CopyWorksheet(SourceWorksheet As Worksheet, AfterDestinationWorksheet As Worksheet) As Worksheet
    
        Dim DestinationWorkbook As Workbook
        Set DestinationWorkbook = AfterDestinationWorksheet.Parent
    
        Dim FirstSheetVisibility As XlSheetVisibility
        FirstSheetVisibility = DestinationWorkbook.Sheets(1).Visible
    
        DestinationWorkbook.Sheets(1).Visible = xlSheetVisible
        SourceWorksheet.Copy Before:=DestinationWorkbook.Sheets(1)
        DestinationWorkbook.Sheets(2).Visible = FirstSheetVisibility
    
        Dim NewWorksheet As Worksheet
        Set NewWorksheet = DestinationWorkbook.Sheets(1)
    
        NewWorksheet.Move After:=AfterDestinationWorksheet
    
        Set CopyWorksheet = NewWorksheet
    
    End Function
    

提交回复
热议问题