基于用户输入的动态隐藏列

问题描述 投票:0回答:1

我有一个工作表,列出了第14行的年份,其中各种值都低于这些年份。我希望有一个用户输入单元格,他们可以输入他们想要查看的年数,同时隐藏其余列。我知道这个代码必须简单,但我似乎很难绕过如何实际编码。我尝试过以下方法:

Sub HideCol()

Range("F14").Select

yearSelect = Range("J8").Value

numrows = Selection.Rows.Count
numCols = Selection.Columns.Count

Selection.Resize(numrows + 0, numCols + yearSelect).Select

Selection.EntireColumnHidden = True


End Sub

我真的认为我是在调整大小的反转之后,这意味着我隐藏了所选区域而不是隐藏其余列。先感谢您,

excel-vba vba excel
1个回答
1
投票

如果我正确理解您的问题,请将您的年份输入单元格更改为F列之前的另一列,否则,您将面临隐藏输入单元格的风险:)

然后将此代码放在数据所在的工作表模块中。根据数据需要对代码进行范围调整。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = Me.Range("D8").Address Then 'i moved input cell to D8

        Application.ScreenUpdating = False

        Range("F14:Z14").EntireColumn.Hidden = False 'this range is the total for the number of years you have

        Dim hideYears As Range
        Set hideYears = Me.Range("F14").Offset(0, Target.Value)
        Set hideYears = Range(hideYears, hideYears.End(xlToRight))

        hideYears.EntireColumn.Hidden = True

    End If

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.