根据单元格的值隐藏excel中的列

时间:2016-04-08 03:52:37

标签: excel vba excel-vba

我的目标是在第3行到第10行中的所有值在该列中为零时隐藏列,因此我在第11行创建公式,它是第3行到第10行的值的总和

基本上我可以创建像这样的代码

If Range("B11").Value = 0 Then
Columns("B:B").EntireColumn.Hidden = True

Else

Columns("B:B").EntireColumn.Hidden = False

End If

If Range("C11").Value = 0 Then
Columns("C:C").EntireColumn.Hidden = True

Else

Columns("C:C").EntireColumn.Hidden = False
End If

但是如何简单地这样做,因为我希望这个宏从B列运行到FV,

或者是否有任何其他解决方案可以实现我的目标?

5 个答案:

答案 0 :(得分:2)

放置良好的循环有助于连接功能:

path.join()

首先取消隐藏所有列,然后删除了对其他声明的需求

编辑:使用此解决方案,您还不需要第11行中的公式。

答案 1 :(得分:2)

我很惊讶没有人写出最简单的答案。

for i = 2 to 178
    if cells(11, i).value = 0 then
        Columns(i).EntireColumn.Hidden = True
    end if
next

答案 2 :(得分:1)

单向的。

Sub test()
Dim iStart  As Long:        iStart = Range("B1").Column
Dim iFin    As Long:          iFin = (Range("FV1").Column) - 1
Dim iCntCol As Long:       iCntCol = iStart 'Col B is #2
    For iCntCol = iStart To iFin 'FV is Col # 178
        If Cells(11, iCntCol).Value = 0 Then
            Columns(iCntCol).EntireColumn.Hidden = True
          Else
            Columns(iCntCol).EntireColumn.Hidden = False
         End If
    Next iCntCol
End Sub

HTH

答案 3 :(得分:1)

性能应该是一个问题,请考虑以下内容

Option Explicit

Sub hide()
Dim found As Range

With Intersect(ActiveSheet.Range("B11:FV11"), ActiveSheet.UsedRange.EntireColumn)
    .EntireColumn.Hidden = False
    .FormulaR1C1 = "=sum(R3C:R10C)"
    Set found = GetZeroColumns(.Cells, 0)
End With
If Not found Is Nothing Then found.EntireColumn.Hidden = True    

End Sub


Function GetZeroColumns(rng As Range, value As Variant) As Range
Dim firstAddress As String
Dim found As Range

With rng
    Set found = .Find(What:=value, LookIn:=xlValues, lookat:=xlWhole)
    If Not found Is Nothing Then
        firstAddress = found.Address
        Set GetZeroColumns = found
        Do
            Set GetZeroColumns = Union(GetZeroColumns, found)
            Set found = .FindNext(found)
        Loop While Not found Is Nothing And found.Address <> firstAddress
    End If
End With
End Function

答案 4 :(得分:1)

我们可以使用更通用的代码来实现这一点,不需要对代码范围进行硬编码,以便可以在许多地方重复使用。请在下面考虑,For...Next循环将测试Selection中的每个单元格。 Selection是当前选定的单元格。因此,只需选择要运行代码的单元格。如果单元格的值等于0,则该列将被标记为隐藏。我也不建议逐一隐藏列,这会使代码不必要地变慢,特别是当工作表中有很多公式或者要隐藏很多列时。所以我所做的只是使用Union函数标记要隐藏的列。然后一次隐藏它们,你可以在代码的最后一行看到它。

Sub HideZerosByColumn()
    Dim iRng As Range
    Dim uRng As Range
    Set uRng = Nothing
    For Each iRng In Selection
        If iRng = 0 And Not IsEmpty(iRng) Then
            If uRng Is Nothing Then Set uRng = iRng Else Set uRng = Union(uRng, iRng)
        End If
    Next iRng
    If Not uRng Is Nothing Then uRng.EntireColumn.Hidden = True
End Sub

在运行代码之前,请选择要考虑的范围。

enter image description here

运行代码后

enter image description here

相关问题