VBA Excel根据行范围中存在的ANY值隐藏列

2jcobegt  于 2023-02-25  发布在  其他
关注(0)|答案(1)|浏览(177)


I看到一个帖子,但不能评论说,我能够成功地使用VBA代码后,几个小时的尝试。
chris neilsen为这篇文章写了这个解决方案:链接
我修改了上面链接中的原始代码来隐藏一列。如果行中存在值2,它就可以工作。但是,问题是如果我将下一行改为1,找到的前2将被忽略,该行将再次隐藏,就好像整个代码只关注新值一样。也许For each循环是错误的?
我的工作表的目标是一个公司报价表。用户将选择预先选定的选项(在本例中为1或2),代码旨在搜索“如果在这些行中找到任何值2,则显示一个条件列供他们填写)。用户表单在我的365Mac版本上不可用。除了一个错误,这段代码工作得很好。

Private Sub Macro2(ByVal Target As Range)
    Dim RangeOfInterest As Range
    Dim TargetRangeOfInterest As Range
    Dim cl As Range
    Dim SearchValue As Variant
    
    'I want to search for the value 2
    '~~~ you probably want to search for the number 2, not the string "2"
    SearchValue = 2
    
    Set RangeOfInterest = Me.Range("I13:I20") '<~~ adjust to suit your needs
    
    Set TargetRangeOfInterest = Application.Intersect(RangeOfInterest, Target)
    If Not TargetRangeOfInterest Is Nothing Then
        With Me.Columns("U").EntireColumn
            For Each cl In TargetRangeOfInterest.Cells
                If cl.Value2 = SearchValue Then
                    ' Reads are faster than Writes, so only change the Hidden state if required
                    If .Hidden Then
                        .Hidden = False 'I want to reveal the hidden row 10 if Value 2 is found
                    End If
                Else  'If there is no value of 2
                    If Not .Hidden Then
                        .EntireColumn.Hidden = True 'hide row 10
                    End If
                End If
            Next
        End With
    End If
End Sub
mzillmmw

mzillmmw1#

A工作表变更:隐藏列

板材模块,例如Sheet1

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    HideMyColumn Target
End Sub

标准模块,例如Module1

Option Explicit

Sub HideMyColumn(ByVal Target As Range)
    
    Const TARGET_RANGE As String = "I13:I20"
    Const SEARCH_VALUE As Variant = 2
    Const HIDE_COLUMN As Variant = "U"
    
    Dim ws As Worksheet: Set ws = Target.Worksheet
    Dim trg As Range: Set trg = ws.Range(TARGET_RANGE)
    Dim irg As Range: Set irg = Intersect(trg, Target)
    If irg Is Nothing Then Exit Sub
       
    With ws.Columns(HIDE_COLUMN)
        If IsNumeric(Application.Match(SEARCH_VALUE, trg, 0)) Then
            If .Hidden Then .Hidden = False
        Else
            If Not .Hidden Then .Hidden = True
        End If
    End With

End Sub

相关问题