根据多行中的值调整VBA代码以隐藏列

时间:2017-11-13 22:33:40

标签: excel vba excel-vba

我有一段代码我曾经根据该列中的值来隐藏列,实际上它会查看某一行下面的列中的所有单元格,如果有一个值,那么它会保留它显示,如果没有,它会隐藏它。

现在我需要它来隐藏来自特定行的值的东西。这是代码:

Sub HideCols()
Dim LC As Integer, j As Integer
Dim LR As Integer, curCnt As Integer
Dim k As Integer
Dim Data As Variant

Application.ScreenUpdating = False

LC = Cells(3, Columns.Count).End(xlToLeft).Column

For j = 6 To LC
    LR = Cells(Rows.Count, j).End(xlUp).Row
    curCnt = 0
    Data = Range(Cells(1, 1), Cells(LR, LC))
    For k = 3 To LR
       If Rows(k).Hidden = False And Data(k, j) <> "" Then _
       curCnt = curCnt + 1
    Next k
    Columns(j).Hidden = curCnt < 2
Next j

Application.ScreenUpdating = True

End Sub

我尝试添加:

Dim i As Long
Dim c As Variant
Dim l As Integer
For i = 6 To j
    For Each c In ActiveSheet.Cells(2, i)
    If Columns(i).Hidden and c.Value Like "Tri-Annual" Then
        ActiveSheet.Columns(i).Hidden = False
    Else
        ActiveSheet.Columns(i).Hidden = True
    End If
    Next c
Next i

这是在下面添加的,所以希望它只会查看第一个宏未隐藏的列,然后隐藏那些在该列中也没有“Tri-Annual”的列。第2行。它确实完成了任务,但我必须运行它两次。有没有更简单的方法呢?

1 个答案:

答案 0 :(得分:1)

试试这个。我想我的方法是正确的。

Sub HideCols()

Dim LC As Long, j As Long
Dim LR As Long, curCnt As Long
Dim k As Long
Dim Data As Variant

Application.ScreenUpdating = False

LC = Cells(3, Columns.Count).End(xlToLeft).Column

For j = 6 To LC
    LR = Cells(Rows.Count, j).End(xlUp).Row
    curCnt = 0
    Data = Range(Cells(1, 1), Cells(LR, LC))
    For k = 3 To LR
       If Rows(k).Hidden = False And Data(k, j) <> "" Then _
       curCnt = curCnt + 1
    Next k
    Columns(j).Hidden = curCnt < 2 Or Cells(2, j).Value <> "Tri-Annual"
Next j

Application.ScreenUpdating = True

End Sub