根据用户选择隐藏Excel列

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

我在单元格B2中有一个验证列表,该列表从ROW 5(G5:BF5)获取列表。

我希望用户能够从验证列表中选择一个值,导致除了从与单元格B2中的值匹配的列标题之外,从G到BF的所有列都被隐藏。

我使用了下面的代码,但始终收到应用程序定义或对象定义的错误。

我正在使用下面的VBA:

工作表>>更改

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$B$2" Then
    Dim the_selection As String
    Dim week_in_review As String
    the_selection = Worksheets("SortHeatMap").Range("B2")
    Dim rep As Integer
    For rep = 8 To 25
    the_column = GetColumnLetter_ByInteger(rep)
    week_in_review = Worksheets("SortHeatMap").Range(column_letter & "5")
    If the_selection = week_in_review Then
    Worksheets("SortHeatMap").Range(the_column & ":" & the_column).EntireColumn.Hidden = False
    Else
    Worksheets("SortHeatMap").Range(the_column & ":" & the_column).EntireColumn.Hidden = True
    End If
    Next rep
    End If

End Sub

以及(在(常规)中的>> >>模块1中的GetColumnLetter_ByInteger中。

Public Function GetColumnLetter_ByInteger(what_number As Integer) As String

    'This section obtains Column letter of selected week.

    GetColumnLetter_ByInteger = ""

    If MyColumn_integer <= 26 Then
    column_letter = Chr(64 + MyColumn_integer)
    End If

    If MyColumn_integer > 26 Then
    column_letter = Chr(Int((MyColumn_integer - 1) / 26) + 64) & Chr(((MyColumn_integer - 1) Mod 26) + 65)
    End If

    GetColumnLetter_ByInteger = column_letter

End Function
vba excel-2010
2个回答
0
投票

这样的事情应该做:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rep As Long, v
    If Target.Address = Me.Range("B2").Address Then
        v = Target.Value
        For rep = 8 To 25
            Me.Columns(rep).Hidden = (Me.Cells(5, rep).Value <> v)
        Next rep
    End If
End Sub

当您进入工作表代码模块时,可以使用Me来引用工作表。

将列号转换为字母是一件很痛苦的事,您根本不需要这样做。


0
投票

此代码将首先隐藏指定范围内的所有列,然后显示您在B2中指定的列。该系统的优点是先前显示的列将位于隐藏的位置。

Private Sub Worksheet_Change(ByVal Target As Range)

    Const TriggerCell As String = "B2"
    Const FirstColumnToHide As String = "G"
    Const LastColumnToHide = "BF"

    Dim Rng As Range
    Dim ClmToShow As Variant

    With Target
        If .Address = Range(TriggerCell).Address Then
            Application.ScreenUpdating = False
            ClmToShow = .Value
            On Error Resume Next
            ClmToShow = Columns(ClmToShow).Column
            If ClmToShow < Columns(FirstColumnToHide).Column Or _
               ClmToShow > Columns(LastColumnToHide).Column Then Exit Sub
            ' if TriggerCell doesn't contain a qualified column reference
            ' this would also be the case if an error occurred at this point

            On Error GoTo 0
            Set Rng = Range(Columns(FirstColumnToHide), Columns(LastColumnToHide))
            Rng.Columns.Hidden = True
            Columns(ClmToShow).Hidden = False
            Application.ScreenUpdating = True
        End If
    End With
End Sub

只要可行,请避免将常量散布在代码中。在这里很容易做到。所有常量都在代码顶部声明。如果将来有更改,可以在不更改代码本身的情况下进行。

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