VBA searching through rows and their associated columns and hide column if there is nothing

心已入冬 提交于 2019-12-19 11:52:57

问题


I am new to VBA programming. I would like to

  • search through the worksheet, and find "N" or "TR" on row 6
  • Then, For every cell in the column of "N" or "TR"
  • if all the cells are blank, then delete/ hide the column
  • if the cells are not blank, highlight the cells that are in blank

This sounds easy but I think it requires two for loops.

 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


回答1:


  1. You don't need two loops.
  2. You mentioned you want to hide column but your code suggest you delete it (I kept solution which hides)
  3. You didn't mentioned which is empty range (which cells are blank) to decide to hide the column- I assumed everything below 11th row.
  4. Here is the code which is tried and tested with some comments inside it.

    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
    


来源:https://stackoverflow.com/questions/17461130/vba-searching-through-rows-and-their-associated-columns-and-hide-column-if-there

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!