根据最长列vba的长度隐藏行

时间:2018-04-30 23:47:25

标签: arrays vba

我有一组7个非连续的列循环,我希望隐藏最长列结束后的所有行(不包含值的单元格)。

For Each Y In Array(4, 10, 16, 22, 28, 34, 40)
For X = 16 To 65
    If wks.Cells(X, Y).Value = "" Then
        wks.Cells(X, Y).EntireRow.Hidden = True
        Else: wks.Cells(X, Y).EntireRow.Hidden = False
    End If
Next X
Next Y

这将覆盖它,除了列的长度不同以及宏完成时,包含数据的某些行已被隐藏。我知道我的东西不太正确,我只是不确定如何调整它。

2 个答案:

答案 0 :(得分:1)

循环列并使用“查找”查找带有值的最后一个。

Sub test()
Dim wks As Worksheet
Set wks = ActiveSheet
wks.Rows("16:65").Hidden = False
Dim y
Dim j As Range
Dim currentmax As Long
For Each y In Array(4, 10, 16, 22, 28, 34, 40)
    Set j = wks.Range(wks.Cells(16, y), wks.Cells(65, y)).Find("*", wks.Cells(16, y), , , xlByRows, xlPrevious)
    If Not j Is Nothing Then
        If j.Row > currentmax Then currentmax = j.Row
    End If
Next y

If currentmax > 16 Then
    wks.Rows(currentmax + 1 & ":65").Hidden = True
End If


End Sub

答案 1 :(得分:0)

Sub TestMe()

    Dim wks         As Worksheet
    Set wks = Worksheets(1)

    Dim myCol       As Variant
    Dim myRow       As Long
    Dim recordRow   As Long : recordRow = 65

    For Each myCol In Array(4, 10, 16, 22, 28, 34, 40)
        For myRow = 16 To 65
            If wks.Cells(myRow, myCol).Value = "" Then
                If recordRow < myRow Then recordRow = myRow
                Exit For
            End If
        Next myRow
    Next myCol

    If myRow < 65 Then wks.Rows("65:" & myRow).EntireRow.Hidden = True

End Sub
  • 引入变量recordRow,它保留列的最低行;
  • 变量进行检查后,第一个for循环退出;
  • 最后,您隐藏了WholeRow,从16开始,以recordRow结束;
  • If myRow < 16需要确保myRow分配了一些值;