如何在不将公式更改为值的情况下隐藏公式输出为 0 的列

How do i hide columns with formula output 0 without changing the formula to value

我是新手,我试图取消隐藏所有列,然后隐藏一行中包含数字“0”的列,问题是该数字是公式的结果。

这是我试过的:

Sub main()
Rows("1:1").EntireColumn.Hidden = False
Dim Col As Range
For Each Col In Columns("E:EX")
    For Each Row In Rows("9:9")
        Col.Hidden = Col.Find("0", , xlFormulas, xlWhole, , , False) Is Nothing
    Next
Next
End Sub

上面代码的结果是所有这些列 (E:Ex) 都被隐藏了。

您走在正确的轨道上,但需要做的细节/改进很少

Private Sub hide_zeroes()

  Dim ws as Worksheet: Set ws = Sheets("Your sheet name") '<- edit me
  Dim lc as Long: lc = ws.Cells(9, Columns.Count).End(xlToLeft).Column 'last active Column
  Dim i as Long

  For i = 1 to lc 'from first till last colummn
     If ws.Cells(9, i) = "0" Then 'if 9th row of Column [i] is 0 Then
         ws.Columns(i).EntireColumn.Hidden = True 'hide entire column
     End If
  Next i

End Sub
  1. 最好用要循环的变量结束 For 循环。有助于保持代码的可读性并避免嵌套循环中出现不必要的错误

    For i = 1 to 99
       'some code
    Next i 'note the i <- 
    
  2. 不需要检查是否是公式,只检查单元格内的值

  3. 最好为您使用的每个变量声明变量名,或者更好的是,使用Option Explicit (代码的第一行) 启用类似于 "strict mode"

  4. 的功能