【问题标题】:VBA searching through rows and their associated columns and hide column if there is nothingVBA搜索行及其关联的列,如果没有则隐藏列
【发布时间】:2013-07-01 22:02:51
【问题描述】:

我是 VBA 编程新手。我愿意

  • 搜索工作表,在第 6 行找到“N”或“TR”
  • 那么,对于“N”或“TR”列中的每个单元格
  • 如果所有单元格都是空白的,则删除/隐藏该列
  • 如果单元格不是空白的,则突出显示空白的单元格

这听起来很简单,但我认为它需要两个 for 循环。

 Sub checkandhide()    
    Set r = Range("6:6")  
    Rows("7:7").Select  
    For Each Cell In r  
        Selection.Find(What:="N", After:=ActiveCell, LookIn:=xlFormulas, LookAt _  
            :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _  
            False, MatchByte:=False, SearchFormat:=False).Activate  
        'search for N  
        Application.Run "hidecolumn"  
    Next  
 End Sub  


Sub hidecolumn()
    Dim target As Range
    Dim dwn As Range

    Set dwn = Range(ActiveCell.End(xlDown).Address)
    ActiveCell.Select

    ActiveCell.Offset(6, 0).Select

    For Each Cell In dwn
        If Cell.Text = "" Then Columns.Delete
    Next      
End Sub    

attached example spreadsheet

【问题讨论】:

  • 您的工作表中有多少(大约)列需要您进行此操作?

标签: vba search loops hide


【解决方案1】:
  1. 您不需要两个循环。
  2. 您提到要隐藏列,但您的代码建议您删除它(我保留了隐藏的解决方案)
  3. 您没有提到决定隐藏该列的空范围(哪些单元格为空白) - 我假设所有内容都低于第 11 行。
  4. 这是经过尝试和测试的代码,其中包含一些 cmets。

    Sub checkandhide()
    Dim r As Range
    Dim Cell As Range
    'don't run it for the complete row but from first to last cell in it
    Set r = Range("A6", Cells(6, Columns.Count).End(xlToLeft))
    
    For Each Cell In r
        'you don't need find if you simply need to check value of the cell
        'let's assume we check for 'N' & 'TR'  but not 'n' or 'tr'
        If Cell.Value = "N" Or Cell.Value = "TR" Then
    
            'there are few possibilities to check if there is any value below _
            row 11 (?!) in analysed column. I would use this one:
            If Cells(Rows.Count, Cell.Column).End(xlUp).Row < 12 Then
                Cell.EntireColumn.Hidden = True
            End If
    
        End If
    Next
    End Sub
    

【讨论】:

  • 非常感谢!这帮助很大!!!!但我还是有问题。当第 6 行显示“N”/“TR”(不隐藏列)时,是否能够突出显示已填充的单元格,如果第 6 行显示“Y”,是否也可以突出显示为空的单元格?
  • 你能不能告诉我在 If Cells(Rows.Count, Cell.Column).End(xlUp).Row
  • 回答第二个 - 检查列中是否有任何内容,此代码转到列中的最后一个单元格,像按 Ctrl+UpArrow 一样向上移动,如果它在行号低于 12 时停止,则为标准满足。
  • 首先-为此提出单独的问题...但是请考虑“突出显示空单元格”-在哪个区域? “Y”列中的所有 1.000.000 行?会非常低效......
  • 非常感谢 KazJaw!你的回答很有帮助,我朝着我的目标迈出了一大步!
猜你喜欢
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
  • 2012-02-17
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
相关资源
最近更新 更多