How to save the range of all hidden columns in VBA for Excel
In VBA for Excel, I need to save the range of all columns in the sheet that are hidden, unfortunately I don't manage to find out how to do this. To put more context, my intent is to save the range of hidden columns of the sheet in a temporary variable, then unhide the columns, save the workbook and re-hide the saved columns, so that the workbook is always saved with all columns visible. I am stuck on the "save the range of hidden columns of the sheet in a temporary variable" step. Thanks for you help.
Ответы
Возможно, существует более эффективный способ добиться того, чего вы хотите, но один из способов - это прокрутить столбцы вашего диапазона, и если столбец скрыт, добавьте его в переменную диапазона, используя 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
На самом деле это довольно простой процесс. В будущем вам действительно нужно поделиться с нами тем, что вы сделали, чтобы попытаться решить проблему.
Я предполагаю, что вы новичок в 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