这可以隐藏列代码更有效吗?

时间:2017-04-22 20:15:57

标签: excel vba excel-vba

我是编写VBA代码的新手 - 如果你可以建议我如何更有效地编写这个隐藏列代码,我将会很好看:

代码的目的是:如果列 F4 中的单元格为空,则隐藏 F 列,依此类推。

Private Sub Worksheet_Change(ByVal Target As Range)

If Range("F4").Value = "" Then
    Columns("F").EntireColumn.Hidden = True
Else
    Columns("F").EntireColumn.Hidden = False
End If

If Range("G4").Value = "" Then
    Columns("G").EntireColumn.Hidden = True
Else
    Columns("G").EntireColumn.Hidden = False
End If

If Range("H4").Value = "" Then
    Columns("H").EntireColumn.Hidden = True
Else
    Columns("H").EntireColumn.Hidden = False
End If

If Range("I4").Value = "" Then
    Columns("I").EntireColumn.Hidden = True
Else
    Columns("I").EntireColumn.Hidden = False
End If

If Range("J4").Value = "" Then
    Columns("J").EntireColumn.Hidden = True
Else
    Columns("J").EntireColumn.Hidden = False
End If

If Range("K4").Value = "" Then
    Columns("K").EntireColumn.Hidden = True
Else
    Columns("K").EntireColumn.Hidden = False
End If

If Range("L4").Value = "" Then
    Columns("L").EntireColumn.Hidden = True
Else
    Columns("L").EntireColumn.Hidden = False
End If

If Range("M4").Value = "" Then
    Columns("M").EntireColumn.Hidden = True
Else
    Columns("M").EntireColumn.Hidden = False
End If

End Sub

2 个答案:

答案 0 :(得分:2)

第6到13列的循环可能会改善:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim c As Long
    For c = 6 To 13
        Columns(c).EntireColumn.Hidden = IsEmpty(Cells(4, c).Value)
    Next
End Sub

答案 1 :(得分:0)

检查: -

Sub Hide_Columns()
Dim c As Range

    For Each c In Range("F4:K4").Cells
        If c.Value = "" Then
            c.EntireColumn.Hidden = True
        End If
    Next c

End Sub

感谢: - )