【问题标题】:How to save the range of all hidden columns in VBA for Excel如何在 VBA for Excel 中保存所有隐藏列的范围
【发布时间】:2020-08-20 12:55:19
【问题描述】:

在 Excel 的 VBA 中,我需要保存工作表中隐藏的所有列的范围,遗憾的是我不知道如何执行此操作。 为了提供更多上下文,我的意图是将工作表的隐藏列范围保存在一个临时变量中,然后取消隐藏列,保存工作簿并重新隐藏保存的列,以便始终保存工作簿并显示所有列. 我被困在“将工作表的隐藏列范围保存在临时变量中” 步骤上。 谢谢你的帮助。

【问题讨论】:

  • 嗨,首先与我们分享您尝试过的任何代码。接下来,我会将其视为 3 个步骤。 1. 列出所有标题。 2. 确定它们是否可见 3. 如果它们不可见,则将它们添加到数组中。然后最后一步是创建实际取消/隐藏标题数组的子。
  • @MarkS.这里我需要获取隐藏列的范围。然后可以运行类似mRange.EntireColumn.Hidden = False

标签: excel vba range hidden


【解决方案1】:

可能有一种更有效的方法来实现您想要的,但一种方法是循环遍历范围的列,如果该列被隐藏,则使用 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 的建议进行了改进

【讨论】:

  • 实际上我想知道是否可以通过使用工作表属性或我可能错过的方法来避免循环。感谢这个函数通过返回隐藏列的范围来回答我的问题。
【解决方案2】:

这实际上是一个非常简单的过程。将来您确实需要与我们分享您为解决问题所做的工作。

我假设您是 vba 的新手,请参阅我在下面的代码中留下的 cmets。

    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

【讨论】:

  • 这可以解决问题,但是我正在寻找一个返回范围的函数。
  • 啊我误解了最终结果是什么
猜你喜欢
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多