簡體   English   中英

遍歷范圍VBA

[英]Loop through the range VBA

尋找一個遍歷該范圍的簡單循環(例如,列A range(“ A5:A15”)),如果該范圍內有一個空白單元格,則需要隱藏與該空白單元格相關聯的整個行/行。

我正在考慮使用類似的方法來適應各種范圍,但會出現“類型不匹配”錯誤。 任何原因

Sub test()

    Dim rng As Range, cell As Variant, ar As Variant
    Dim Rng1 As Range, Rng2 As Range, Rng3 As Range, Rng4 As Range

    Dim MyArray(1 To 4) As Range

      With ThisWorkbook.Worksheets("sheet1")

      'Set MyArray = rng


       Set MyArray(1) = Range("O8:O17")
       Set MyArray(2) = Range("O55:O64")
       Set MyArray(3) = Range("G37:G46")
       Set MyArray(4) = Range("G89:G98")


        'ar = Array(Rng1, Rng2, Rng3, Rng4)

        'Set rng = .Range("O8:O17")

        For Each cell In MyArray

            If Len(cell.Value) < 1 Then

               cell.EntireRow.Hidden = True

            End If

        Next cell

    End With

End Sub

像這樣的東西:

您可以將其放在一個主題中:

For Each cell In Range("A5:A15")

    If Len(cell.Value) < 1 Then

        cell.EntireRow.Hidden = True

    End If

Next
For Each cell In Range("A40:A55")

    If Len(cell.Value) < 1 Then

        cell.EntireRow.Hidden = True

    End If

Next

新答案:

Dim rng As Range, cell As Variant, ar As Variant
Dim Rng1 As Range, Rng2 As Range, Rng3 As Range, Rng4 As Range

Dim MyArray(1 To 4) As Range

  With ThisWorkbook.Worksheets("sheet1")

  'Set MyArray = rng


   Set MyArray(1) = Range("O8:O17")
   Set MyArray(2) = Range("O55:O64")
   Set MyArray(3) = Range("G37:G46")
   Set MyArray(4) = Range("G89:G98")


    'ar = Array(Rng1, Rng2, Rng3, Rng4)

    'Set rng = .Range("O8:O17")
Dim i As Integer

    For i = LBound(MyArray) To UBound(MyArray)

            For Each cell In MyArray(i)

             If Len(cell.Value) < 1 Then

               cell.EntireRow.Hidden = True

            End If

        Next

    Next

End With

嘗試以下

Option Explicit
Sub youcouldhaveatleasttriedtodosomethingyourself()

Dim r1 As Range, r2 As Range, c As Range, target As Range

With Workbooks(REF).Sheets(REF)
    Set r1 = .Range("A1:A54")
    Set r2 = .Range("F3:F32")

    Set target = Application.Union(r1, r2) 
    For Each area In target.Areas
        For Each c In area
            If c.Value = vbNullString Then .Rows(c.Row).EntireRow.Hidden = True
        Next c
    Next area
End With

End Sub

請注意,我現在設置了兩個示例范圍。 您始終可以將更多范圍變量添加到Union函數。

嘗試:

Option Explicit

Sub test()

    Dim rng As Range, cell As Range

    With ThisWorkbook.Worksheets("Sheet1")

        Set rng = .Range("A5:A15")

        For Each cell In rng

            If cell.Value = "" Then

                .Rows(cell.Row).EntireRow.Hidden = True

            End If

        Next cell

    End With

End Sub

這充分利用了Excel VBA模型。 我猜它比上面的要快,但是還沒有進行性能測試。

Dim Cell As Range
For Each Cell In Range("A5:A15").SpecialCells(xlCellTypeBlanks)
   Cell.EntireRow.Hidden = True
Next

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM