programing

시트를 복사하고 결과 시트 개체를 가져오시겠습니까?

muds 2023. 4. 26. 23:49
반응형

시트를 복사하고 결과 시트 개체를 가져오시겠습니까?

워크시트를 복사할 때 새 시트의 워크시트 개체를 가져오는 쉬운/짧은 방법이 있습니까?

ActiveWorkbook.Sheets("Sheet1").Copy after:=someSheet

알고 보니.복사 방법은 워크시트 개체 대신 부울을 반환합니다.그렇지 않았다면, 나는 할 수 있었을 것입니다.

set newSheet = ActiveWorkbook.Sheets("Sheet1").Copy after:=someSheet

그래서 저는 목적어를 얻기 위해 25줄의 코드를 썼습니다.복사본 앞에 모든 시트를 나열하고, 다음에 모든 시트를 나열하고, 두 번째 목록에만 있는 시트를 확인합니다.

저는 더 우아하고 짧은 해결책을 찾고 있습니다.

Dim sht 

With ActiveWorkbook
   .Sheets("Sheet1").Copy After:= .Sheets("Sheet2")
   Set sht = .Sheets(.Sheets("Sheet2").Index + 1)
End With

저는 제가 마침내 이 문제를 해결했다고 믿습니다. 그것은 또한 저를 미치게 하고 있습니다!MS가 Copy에게 Add 메서드와 같은 시트 객체를 반환하도록 했다면 정말 좋았을 것입니다.

문제는, VBA가 새로 복사한 시트를 할당하는 인덱스가 실제로 결정되지 않았다는 것입니다.다른 사람들이 지적했듯이, 그것은 숨겨진 시트에 매우 의존합니다.사실 Sheets(n)라는 표현은 실제로 "n번째 가시적인 시트"로 해석된다고 생각합니다.따라서 모든 시트의 가시적 속성을 테스트하는 루프를 작성하지 않는 한 코드에서 이를 사용하는 것은 위험합니다. 워크북이 사용자가 시트의 가시적 속성을 조작할 수 없도록 보호하지 않는 한 위험합니다.너무 어려워요...

이 딜레마에 대한 저의 해결책은 다음과 같습니다.

  1. LAST 시트를 표시합니다(임시인 경우에도).
  2. 그 시트 뒤에 복사하세요.인덱스 시트가 있어야 합니다.세어보세요
  3. 필요한 경우 이전의 마지막 시트를 다시 숨깁니다. 이제 인덱스 시트가 있습니다.카운트-1
  4. 새 시트를 원하는 위치로 이동합니다.

여기 제 코드가 있습니다. 이제 방탄 처리가 된 것 같습니다.

Dim sh as worksheet
Dim last_is_visible as boolean

With ActiveWorkbook
    last_is_visible = .Sheets(.Sheets.Count).Visible
    .Sheets(Sheets.Count).Visible = True
    .Sheets("Template").Copy After:=.Sheets(Sheets.Count)
    Set sh=.Sheets(Sheets.Count)
    if not last_is_visible then .Sheets(Sheets.Count-1).Visible = False 
    sh.Move After:=.Sheets("OtherSheet")
End With

저 같은 경우에는 이런 것이 있었습니다(숨겨진 시트를 나타내는 H).

1... 2... 3(H)... 4(H)... 5(H)... 6... 7... 8(H)... 9(H)

.복사 후:=.시트(2)는 실제로 다음에 표시되는 시트 앞에 새 시트를 만듭니다. 즉, 새 인덱스 6이 됩니다. 예상한 대로 인덱스 3이 아닙니다.

그게 도움이 되길 바래 ;-)

제가 사용한 또 다른 해결책은 시트를 인덱스를 알고 있는 위치에 복사하는 것입니다.거기서 필요한 것은 무엇이든 쉽게 참조할 수 있고, 그 후에는 원하는 곳으로 자유롭게 이동할 수 있습니다.

이와 같은 것:

Worksheets("Sheet1").Copy before:=Worksheets(1)
set newSheet = Worksheets(1)
newSheet.move After:=someSheet

업데이트:

Dim ThisSheet As Worksheet
Dim NewSheet As Worksheet
Set ThisSheet = ActiveWorkbook.Sheets("Sheet1")
ThisSheet.Copy
Set NewSheet = Application.ActiveSheet

Daniel Labelle의 제안으로 업데이트됨:

숨겨진 시트를 처리하려면 소스 시트를 표시하고 복사한 다음ActiveSheet참조를 새 시트로 되돌리고 가시성 설정을 재설정하는 방법:

Dim newSheet As Worksheet
With ActiveWorkbook.Worksheets("Sheet1")
    .Visible = xlSheetVisible
    .Copy after:=someSheet
    Set newSheet = ActiveSheet
    .Visible = xlSheetHidden ' or xlSheetVeryHidden
End With

저는 이 게시물이 1년이 넘었다는 것을 알고 있지만, 저는 시트 복사와 숨겨진 시트로 인한 예상치 못한 결과와 관련된 동일한 문제에 대한 답을 찾고자 여기에 왔습니다.위의 어느 것도 제 워크북의 구조 때문에 제가 원하는 것에 맞지 않았습니다.본질적으로 그것은 매우 많은 시트를 가지고 있고 표시되는 것은 사용자가 특정 기능을 선택하는 것에 의해 구동됩니다. 게다가 보이는 시트의 순서는 저에게 중요했기 때문에 저는 그것들을 망치고 싶지 않았습니다.그래서 제 최종 해결책은 복사된 시트에 대한 Excels 기본 명명 규칙에 의존하고 새 시트의 이름을 명시적으로 변경하는 것이었습니다.아래 코드 샘플(별도로, 내 워크북은 42장이고 7장만 영구적으로 볼 수 있습니다.after:=Sheets(Sheets.count)42장 가운데에 복사한 시트를 넣어주세요. 그때 어떤 시트가 보이는지에 따라요.

        Select Case DCSType
        Case "Radiology"
            'Copy the appropriate Template to a new sheet at the end
            TemplateRAD.Copy after:=Sheets(Sheets.count)
            wsToCopyName = TemplateRAD.Name & " (2)"
            'rename it as "Template"
            Sheets(wsToCopyName).Name = "Template"
            'Copy the appropriate val_Request to a new sheet at the end
            valRequestRad.Copy after:=Sheets(Sheets.count)
            'rename it as "val_Request"
            wsToCopyName = valRequestRad.Name & " (2)"
            Sheets(wsToCopyName).Name = "val_Request"
        Case "Pathology"
            'Copy the appropriate Template to a new sheet at the end
            TemplatePath.Copy after:=Sheets(Sheets.count)
            wsToCopyName = TemplatePath.Name & " (2)"
            'rename it as "Template"
            Sheets(wsToCopyName).Name = "Template"
            'Copy the appropriate val_Request to a new sheet at the end
            valRequestPath.Copy after:=Sheets(Sheets.count)
            wsToCopyName = valRequestPath.Name & " (2)"
            'rename it as "val_Request"
            Sheets(wsToCopyName).Name = "val_Request"
    End Select

어쨌든, 다른 사람에게 유용할 경우를 대비하여 게시되었습니다.

이 질문은 정말 오래된 것입니다. 하지만 얼마 전에 여기서 어떤 활동이 있었고 10년 후에도 여전히 제게 필요한 모든 답을 주었기 때문에, 저는 제가 그것을 하는 방법을 공유하고 싶습니다.

이 스레드를 읽고 난 후, 저는 아마의 해결책이 더 마음에 들더라도 티그레갈리스의 대답이 정말 흥미롭다는 것을 알았습니다.그러나 새로운 워크북 이전/이후 또는 새로운 워크북에 복사할 것인지에 대한 선택과 함께 원래 Excel 동작을 반영하는 것은 없었습니다.필요에 따라 나만의 기능을 적었고, 엑셀의 기능과 좀 더 가깝게 만들기 위해 워크시트뿐만 아니라 시트를 다룰 수 있도록 했습니다.

관심 있는 분들을 위해 제 코드는 다음과 같습니다.

Function CopySheet(ByVal InitSh As Object, Optional ByVal BeforeSh As Object, Optional ByVal AfterSh As Object) As Object
'Excel doesn't provide any reliable way to get a pointer to a newly copied sheet. This function allows to make it
'Arguments: - InitSh : The sheet we want to copy
'           - BeforeSh : The sheet before the one we want the copy to be placed
'           - AfterSh : The sheet after the one we want the copy to be placed
'Return   : - Returns the newly copied sheet. If BeforeSh and AfterSh are not givent to the sub, the sheet is created in a new workbook. In the case both are given, BeforeSh is used
'             To beknown : if the InitSh is not visible, the new one won't be visible except if InitWks is the first of the workbook !

    Dim isBefore As Boolean
    Dim isAfter As Boolean
    Dim Wkb As Workbook
    
    'If there is before or after, we need to know the workbook where the new sheet is copied, if not we need to set up a new workbook
    If Not BeforeSh Is Nothing Then
        isBefore = True
        Set Wkb = BeforeSh.Parent
    ElseIf Not AfterSh Is Nothing Then
        isAfter = True
        Set Wkb = AfterSh.Parent
    Else
        Set Wkb = Application.Workbooks.Add(xlWBATWorksheet)
    End If

    'To be able to find the new worksheet, we need to make sure the first sheet of the destination workbook is visible and make the copy before it
    Dim FirstWksVisibility As XlSheetVisibility
    FirstWksVisibility = Wkb.Sheets(1).Visible
    Wkb.Sheets(1).Visible = xlSheetVisible

    InitSh.Copy before:=Wkb.Sheets(1)

    'Restore the initial visibility of the first worksheet of the workbook, that is now the sheet number 2 as we copied one in front of it
    Wkb.Sheets(2).Visible = FirstWksVisibility
    
    'Finaly, move the sheet accordingly to otpional arguments BeforeWks or AfterWks
    Dim TempSh As Object
    Set TempSh = Wkb.Sheets(1)
    If isBefore Then
        TempSh.Move before:=BeforeSh
    ElseIf isAfter Then
        TempSh.Move after:=AfterSh
    Else
        'If no optional arguments, we made a new workbook and we need to erase the blank worksheet that was created with it if the new sheet is visible (we cant if it's not visible)
        If TempSh.Visible = xlSheetVisible Then
            Dim Alert As Boolean
            Alert = Application.DisplayAlerts
            Application.DisplayAlerts = False
            Wkb.Sheets(2).Delete
            Application.DisplayAlerts = Alert
        End If
    End If
    
    Set CopySheet = TempSh
End Function

저는 워크시트와 차트를 사용하여 제 코드를 광범위하게 테스트하려고 노력했고, 제 생각에 그것은 그것이 의도했던 것과 같습니다.원본 시트가 없는 경우 원본 시트가 워크북의 첫 번째 시트인 경우를 제외하고는 복사된 시트가 표시되지 않습니다.

@Tim Williams에 대한 댓글이어야 하는데, 제가 처음 올린 글이라 댓글을 달 수가 없습니다.

이것은 숨겨진 시트와 관련하여 @RbarryYoung이 언급한 문제의 예입니다.마지막 시트 뒤에 복사본을 넣으려다가 마지막 시트가 숨겨져 있는 경우 문제가 발생합니다.마지막 시트가 숨겨져 있으면 항상 가장 높은 지수를 유지하기 때문에 다음과 같은 것이 필요한 것 같습니다.

Dim sht As Worksheet

With ActiveWorkbook
   .Sheets("Sheet1").Copy After:=.Sheets(.Sheets.Count)
   Set sht = .Sheets(.Sheets.Count - 1)
End With

숨겨진 첫 번째 시트 앞에 복사하려고 할 때와 유사한 상황입니다.

여기서 이미 언급했듯이 시트를 맨 왼쪽(색인 = 1)으로 복사/수정한 다음 변수에 할당한 다음 원하는 위치로 이동합니다.

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

Trevor Norman의 방법을 기반으로 시트를 복사하고 새 시트에 참조를 반환하는 기능을 개발했습니다.

  1. 보이지 않으면 마지막 시트(1) 숨기기 취소
  2. 소스 시트(2)를 마지막 시트(1) 뒤에 복사합니다.
  3. 새 시트(3)에 대한 참조를 설정합니다. 즉, 마지막 시트(1) 뒤에 있는 시트입니다.
  4. 필요한 경우 마지막 시트(1) 숨기기

코드:

Function CopySheet(ByRef sourceSheet As Worksheet, Optional ByRef destinationWorkbook As Workbook) As Worksheet

    Dim newSheet As Worksheet
    Dim lastSheet As Worksheet
    Dim lastIsVisible As XlSheetVisibility

    If destinationWorkbook Is Nothing Then Set destinationWorkbook = sourceSheet.Parent

    With destinationWorkbook
        Set lastSheet = .Worksheets(.Worksheets.Count)
    End With

    ' store visibility of last sheet
    lastIsVisible = lastSheet.Visible
    ' make the last sheet visible
    lastSheet.Visible = xlSheetVisible

    sourceSheet.Copy After:=lastSheet
    Set newSheet = lastSheet.Next

    ' restore visibility of last sheet
    lastSheet.Visible = lastIsVisible

    Set CopySheet = newSheet

End Function

이렇게 하면 항상 복사된 시트가 대상 워크북 끝에 삽입됩니다.

이 후에는 이동, 이름 변경 등을 수행할 수 있습니다.

용도:

Sub Sample()

    Dim newSheet As Worksheet

    Set newSheet = CopySheet(ThisWorkbook.Worksheets("Template"))

    Debug.Print newSheet.Name

    newSheet.Name = "Sample" ' rename new sheet
    newSheet.Move Before:=ThisWorkbook.Worksheets(1) ' move to beginning

    Debug.Print newSheet.Name

End Sub

또는 동작/인터페이스를 기본 제공 복사 방법(예: 사전/사후)과 더 유사하게 하려면 다음을 사용할 수 있습니다.

Function CopySheetTo(ByRef sourceSheet As Worksheet, Optional ByRef beforeSheet As Worksheet, Optional ByRef afterSheet As Worksheet) As Worksheet

    Dim destinationWorkbook As Workbook
    Dim newSheet As Worksheet
    Dim lastSheet As Worksheet
    Dim lastIsVisible As XlSheetVisibility

    If Not beforeSheet Is Nothing Then
        Set destinationWorkbook = beforeSheet.Parent
    ElseIf Not afterSheet Is Nothing Then
        Set destinationWorkbook = afterSheet.Parent
    Else
        Set destinationWorkbook = sourceSheet.Parent
    End If

    With destinationWorkbook
        Set lastSheet = .Worksheets(.Worksheets.Count)
    End With

    ' store visibility of last sheet
    lastIsVisible = lastSheet.Visible
    ' make the last sheet visible
    lastSheet.Visible = xlSheetVisible

    sourceSheet.Copy After:=lastSheet
    Set newSheet = lastSheet.Next

    ' restore visibility of last sheet
    lastSheet.Visible = lastIsVisible

    If Not beforeSheet Is Nothing Then
        newSheet.Move Before:=beforeSheet
    ElseIf Not afterSheet Is Nothing Then
        newSheet.Move After:=afterSheet
    Else
        newSheet.Move After:=sourceSheet
    End If

    Set CopySheetTo = newSheet

End Function

숨겨진 워크시트로 인해 새 워크시트 색인이 원본 워크시트의 어느 쪽에서도 순차적이지 않게 되는 것이 맞습니다.전에 복사하는 거라면 레이첼의 대답이 효과가 있다는 걸 알았어요.하지만 나중에 복사할 경우에는 조정해야 합니다.

모형을 표시하고 복사한 후에는 소스를 복사하기 전이든 후이든 새 워크시트 개체가 활성화된 시트가 됩니다.

기본 설정으로 다음을 대체할 수 있습니다.

Set newSheet = .Previous 트포 함세와 newSheet = Application.ActiveSheet.

이것이 여러분 중 일부에게 도움이 되기를 바랍니다.

저도 같은 요구사항이 있어서 답을 찾다가 이 실타래에 도달했습니다.다양한 옵션을 확인하는 동안 Excel이 저장하는 참조 체인(아래 샘플)을 사용하여 새 시트에 쉽게 액세스할 수 있다는 것을 알게 되었습니다.엑셀은 시트가 참조하는 링크드 리스트 같은 것을 유지하고 있는 것 같습니다.

'Example:
ActiveWorkbook.Sheets("Sheet1").Copy After:=someSheet
set newSheet = someSheet.Next

마찬가지로 다른 시트를 '앞'에 삽입한 시트도 마찬가지입니다.

ActiveWorkbook.Sheets("Sheet1").Copy Before:=someSheet
set newSheet = someSheet.Previous

소스 시트가 숨겨져 있더라도 작동합니다.원본 시트가 숨겨져 있으면 워크시트가 복사되지만 새 시트도 숨겨져 있습니다!

저는 시트에 대한 신뢰할 수 있는 일반적인 "랩퍼" 기능을 만들려고 노력해 왔습니다.여러 프로젝트에서 수년간 재사용할 수 있는 복사 방법.

저는 여기서 여러 가지 접근법을 시도해 보았는데, Mark Moore의 대답만이 모든 시나리오에서 신뢰할 수 있는 솔루션이라는 것을 알게 되었습니다.즉, "템플릿 (2)" 이름을 사용하여 새 시트를 식별합니다.

저의 경우, "ActiveSheet 방법"을 사용하는 솔루션은 일부 경우에는 대상 워크북이 비활성화되거나 숨겨진 워크북에 있었기 때문에 쓸모가 없었습니다.

마찬가지로 워크북 중 일부는 숨겨진 시트가 여러 위치에 표시되는 시트와 혼합되어 있습니다. 처음, 중간, 끝에 표시되는 시트와 숨겨진 시트의 순서에 따라 이전: 및 이후: 옵션을 사용하는 솔루션도 신뢰할 수 없습니다.소스 시트가 숨겨져 있을 때 추가 요인과 함께 표시됩니다.

따라서 몇 번의 재작성 후 다음과 같은 래퍼 기능을 갖게 되었습니다.

'***************************************************************************
'This is a wrapper for the worksheet.Copy method.
'
'Used to create a copy of the specified sheet, optionally set it's name, and return the new
' sheets object to the calling function.
'
'This routine is needed to predictably identify the new sheet that is added. This is because
' having Hidden sheets in a Workbook can produce unexpected results in the order of the sheets,
' eg when adding a hidden sheet after the last sheet, the new sheet doesn't always end up
' being the last sheet in the Worksheets collection.
'***************************************************************************
Function wsCopy(wsSource As Worksheet, wsAfter As Worksheet, Optional ByVal sNewSheetName As String) As Worksheet

    Dim Ws              As Worksheet

    wsSource.Copy After:=wsAfter
    Set Ws = wsAfter.Parent.Sheets(wsSource.Name & " (2)")

    'set ws Name if one supplied
    If sNewSheetName <> "" Then
        Ws.Name = sNewSheetName
    End If
    Set wsCopy = Ws
End Function

참고: 소스 시트의 이름이 27자를 초과하는 경우에도 문제가 발생합니다. 최대 시트 이름은 31자이지만 일반적으로 이 솔루션은 제가 제어합니다.

이전 게시물이지만 시트를 숨기거나 이름에 접미사를 추가하는 것에 대해 확신할 수 없었습니다.

제 접근 방식은 다음과 같습니다.

Sub DuplicateSheet()
    Dim position As Integer
    Dim wbNewSheet As Worksheet
    position = GetFirstVisiblePostion

    ThisWorkbook.Worksheets("Original").Copy Before:=ThisWorkbook.Sheets(position)
    Set wbNewSheet = ThisWorkbook.Sheets(position)

    Debug.Print "Duplicated name:" & wbNewSheet.Name, "Duplicated position:" & wbNewSheet.Index

End Sub

Function GetFirstVisiblePostion() As Integer
    Dim wbSheet As Worksheet
    Dim position As Integer
    For Each wbSheet In ThisWorkbook.Sheets
        If wbSheet.Visible = xlSheetVisible Then
            position = wbSheet.Index
            Exit For
        End If
    Next
    GetFirstVisiblePostion = position
End Function

이에 대한 나의 간단한 해결책을 다음 코드와 공유하고 싶었습니다.

Sub copy_sheet(insheet As String, newsheet As String)
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Sheets(newsheet).Delete
ThisWorkbook.Sheets(insheet).Copy before:=ThisWorkbook.Sheets(1)
For Each ws In ThisWorkbook.Worksheets
    If (InStr(ws.Name, insheet) > 0 And InStr(ws.Name, "(") > 0) Then
        ThisWorkbook.Sheets(ws.Name).Name = newsheet
        Exit For
    End If
Next
Application.DisplayAlerts = True
End Sub

시트를 복사할 때마다 결과 "복사된" 시트에는 항상 원래 시트의 이름과 대괄호로 묶은 번호가 표시됩니다.원래 시트에 괄호로 묶은 숫자 이름이 없는 한 이 작업은 항상 100% 작동합니다.

시트를 복사한 다음, 1) 원래 이름을 포함하고 2) 괄호로 묶인 번호를 가진 시트를 찾는 모든 시트 이름을 반복한 다음 시트 이름을 바꿉니다.

저는 OP와 같은 문제가 있었지만, 숨겨진 매우 숨겨진 시트가 추가되었습니다.

{set last_sheet = 이 워크북과 같은 것을 사용하여 마지막 시트를 찾습니다.워크시트(이 워크북).워크시트.Excel이 숨겨진 워크시트를 카운트하지 않으므로 Count)}이(가) 작동하지 않으므로 위치 번호 {last_sheet}이(가) 작동하지 않습니다.인덱스 +1}이(가) 너무 높아서 오류가 발생합니다.

대신에 저는 위치를 찾기 위해 루프를 만들었습니다.

Dim w as Workbook, s as Worksheet, template_sheet as worksheet, last_sheet as Worksheet, new_sheet as Worksheet
    
' find the position of the last sheet
  For Each s in w.Workbooks
    If s.Visible = xlSheetVisible then
      Set last_sheet = s
    End if
  Next
    
' make the sheet to be copied visible, copy it and hide it again
  w.Worksheets("template_sheet").Visible = xlHidden
  w.Worksheets("template_sheet").Copy After:=last_sheet
  w.Worksheets("template_sheet").Visible = xlVeryHidden
        
' reference the new sheet that was just added
  Set new_sheet = Worksheets(last_sheet.index + 1)

여기서 이미 제시한 여러 답변을 비교한 결과, 가장 우수한 답변도 항상 두 개의 시트 작업에 의존한다는 것을 알게 되었습니다. 하나는 먼저 시트를 복사한 다음 다른 하나는 원하는 위치로 이동하는 것입니다. 하지만, 시트의 정확한 순서에 따라 숨겨진 시트와 동일한 문제가 발생하는 이동 작업은 설명되지 않습니다.숨겨진 것들을 포함하는 것은 어떤 이유로든 중요합니다.

다음은 숨겨진 시트와 상관없이 대상 시트를 워크북의 시트 인덱스에 정확한 위치로 복사할 수 있는 대체 방법입니다.그것은 Sat의 구문에 의해 단순화된 Tim Williams의 대답의 기본 논리를 감싸고 엑셀이 후드 아래에서 무엇을 하든 항상 시트 바로 의 위치에 시트를 복사하고 싶어한다는 Trevor Norman의 통찰력을 강조합니다.

Function CopySheetBefore(ByRef copyTarget As Worksheet, ByRef positionTarget As Worksheet) As Worksheet
Dim visibilityState As XlSheetVisibility, VeryHiddenTarget As Boolean

'record starting visibilities and reset as needed:
visibilityState = positionTarget.Visible
If Not (copyTarget Is positionTarget) Then
    VeryHiddenTarget = (copyTarget.Visible = xlSheetVeryHidden)
Else
    'leave it False to preclude redundant action below...\/
End If
positionTarget.Visible = xlSheetVisible
If VeryHiddenTarget Then copyTarget.Visible = xlSheetVisible

'copy sheet and set return variable:
copyTarget.Copy before:=positionTarget
Set CopySheetBefore = positionTarget.Previous

'reset visibilities to initial states:
positionTarget.Visible = visibilityState
If copyTarget Is positionTarget Then
    CopySheetBefore.Visible = visibilityState
    Exit Function 'to preclude redundant actions below
End If
If VeryHiddenTarget Then
    copyTarget.Visible = xlSheetVeryHidden
    CopySheetBefore.Visible = xlSheetVeryHidden
End If
End Function

매우 숨겨진 시트를 복사하지 않을 것이라는 것을 알고 있다면 기능이 상당히 단순화되어 다음과 같습니다.

Function CopySheetBefore(ByRef copyTarget As Worksheet, ByRef positionTarget As Worksheet) As Worksheet
Dim visibilityState As XlSheetVisibility

'record starting visibility and reset:
visibilityState = positionTarget.Visible
positionTarget.Visible = xlSheetVisible

'copy sheet and set return variable:
copyTarget.Copy before:=positionTarget
Set CopySheetBefore = positionTarget.Previous

'reset visibility to initial state:
positionTarget.Visible = visibilityState
If copyTarget Is positionTarget Then
    CopySheetBefore.Visible = visibilityState
End If
End Function

이렇게 하면 해당 위치 대상의 가시성 또는 다른 주변 시트의 가시성에 관계없이 복사된 시트를 항상 대상 위치 바로 앞에 인덱스 위치에 삽입합니다.

이전 대신 어떤 시트 뒤에 배치해야 하는지를 생각하는 데 전념한다면(또는 구체적으로 마지막 시트 인덱스에 삽입할 수 있기를 원하는 경우) 논리는 기본적으로 동일하지만, 마지막 시트가 숨겨져 있더라도 이 시트를 완성하는 데 필요한 조건은 조금 더 복잡합니다.

Function CopySheetAfter(ByRef copyTarget As Worksheet, ByRef positionTarget As Worksheet) As Worksheet
Dim visibilityState As XlSheetVisibility
Dim CopyAfterLast as Boolean

CopyAfterLast = (positionTarget.index = sheets.count)

'record starting visibility and reset:
If CopyAfterLast Then
    visibilityState = positionTarget.Visible
    positionTarget.Visible = xlSheetVisible
Else
    visibilityState = positionTarget.Next.Visible
    positionTarget.Next.Visible = xlSheetVisible
End If

'copy sheet and set return variable:
copyTarget.Copy after:=positionTarget
Set CopySheetAfter = positionTarget.Next

'reset visibility to initial state:
If CopyAfterLast Then
    positionTarget.Visible = visibilityState
Else
    positionTarget.Next.Next.Visible = visibilityState
End If
If copyTarget Is positionTarget Then
    CopySheetAfter.Visible = visibilityState
End If
End Function

언급URL : https://stackoverflow.com/questions/7692274/copy-sheet-and-get-resulting-sheet-object

반응형