Excel 용 VBA에서 숨겨진 모든 열의 범위를 저장하는 방법

Aug 20 2020

VBA for Excel에서 숨겨진 시트의 모든 열 범위를 저장해야합니다. 안타깝게도이 작업을 수행하는 방법을 찾을 수 없습니다. 더 많은 컨텍스트를 제공하기 위해 내 의도는 시트의 숨겨진 열 범위를 임시 변수에 저장 한 다음 열 숨기기를 해제하고 통합 문서를 저장 한 다음 저장된 열을 다시 숨기면 통합 문서가 항상 모든 열이 표시되도록 저장됩니다. . 나는 "임시 변수에 시트의 숨겨진 열 범위 저장" 단계 에 갇혀 있습니다. 도와 주셔서 감사합니다.

답변

romulax14 Aug 20 2020 at 20:28

원하는 것을 달성하는 더 효율적인 방법이있을 수 있지만 한 가지 방법은 범위의 열을 반복하고 열이 숨겨져있는 경우를 사용하여 범위 변수에 추가하는 것 Union입니다.
예를 들어 변수의 숨겨진 모든 열을 변수 mInitialRange에 저장한다고 가정 해 보겠습니다 mHiddenColumns. 이것은 당신에게 줄 것입니다 :

Dim mInitialRange As Range, mHiddenColumns As Range
For Each mcolumn In mInitialRange.Columns
    If mcolumn.Hidden Then
        If mHiddenColumns Is Nothing Then
            Set mHiddenColumns = mcolumn
        Else
            Set mHiddenColumns = Union(mHiddenColumns, mcolumn)
        End If
    End If
Next mcolumn

편집 : @BigBen 조언에 따라 개선됨

Veegore Aug 20 2020 at 20:21

실제로는 매우 간단한 과정입니다. 앞으로 문제를 해결하기 위해 한 일을 우리와 공유해야합니다.

나는 당신이 이것을 요구하는 vba를 처음 사용한다고 가정합니다. 아래 코드에 남긴 주석을 참조하십시오.

    Sub runme()
Dim HiddenColumns(), size As Integer
    'Using a seperate counter, loop through your range of data.
    'If you find a hidden column redim our hidden columns array and add that row's number to the array
    'then increase our seperate counter
    size = 0
    For i = 1 To 12 'Change this to your range
        If Columns(i).Hidden = True Then
            ReDim Preserve HiddenColumns(size) 'Redim and preserve the array to our "size" variable (which will always be one more than the current array size
            HiddenColumns(size) = i
            size = size + 1
        End If
    Next i

    'Now we want to loop through our array and flip all the columns that were hidden to shown
    'You can add this to the original array building loop to be more efficent I'm just breaking it up here
    'for demonstration purposes
    For i = 0 To size - 1
        Worksheets("Sheet1").Columns(HiddenColumns(i)).Hidden = False
    Next i

    'Call your workbook saving here
    ThisWorkbook.Save

    'Now loop through our array of columns once more to rehide them
    For i = 0 To size - 1
        Worksheets("sheet1").Columns(HiddenColumns(i)).Hidden = True
    Next i
End Sub