首页 文章

VBA插入行忽略隐藏列

提问于
浏览
0

我有代码在选择时插入行与预定义的公式和上面的行格式 . 但是,在插入之前,某些列可能是隐藏的,并且在执行插入时,新行中的所有格式都会因隐藏列而偏移 .

目前我找到了临时解决方案 - 在插入之前我展开了所有隐藏的列 .

是否有一种方法可以简单地避免在_937609中进行偏移和粘贴格式,包括隐藏的格式,而不扩展隐藏的列?

Range("A:BH").EntireColumn.Hidden = False

ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats

'then goes code to insert formulas in each cell

1 回答

  • 1

    一个解决方案是基于 John Coleman 的评论开发的(但我仍然觉得应该有更优雅的解决方案,比如复制格式时的 IncludeHiddenRows = True ):

    Dim n As Variant
        Dim HidRange As Range
        Dim HidCol As Range
        Application.ScreenUpdating = False
        For n = 1 To 182 'make a snapshot (=HidRange) of currently hidden columns
            Set HidCol = ActiveWorkbook.Sheets("tests2").columnS(n)
            If HidCol.Hidden = True Then
                If HidRange Is Nothing Then
                    Set HidRange = HidCol
                Else
                    Set HidRange = Union(HidCol, HidRange)
                End If
            End If
        Next n
    
        If Not HidRange Is Nothing Then 'Unhide the hidden columns
            HidRange.EntireColumn.Hidden = False
        End If
    
        'perform copying formats etc.
    
        If Not HidRange Is Nothing Then 'Return to initial state
            HidRange.EntireColumn.Hidden = True
        End If
       Application.ScreenUpdating = True
    

相关问题