使用VB隐藏行

时间:2018-03-22 18:55:49

标签: vba excel-vba excel

我的目标是隐藏包含一个充满红色的单元格的每一行。这是我的代码:

Sub AstInv()
    Dim myTable As ListObject
    Dim myArray As Variant

    Set myTable = ActiveSheet.ListObjects("Sheet2")
    Set myArray = myTable.ListColumns("Código de Barras2").Range

    For Each cell In myArray
        If Rng.Interior.Color = vbRed Then
            rw.EntireRow.Hidden = True
        End If
    Next
End Sub

每次运行时,我都会收到此错误:

  

编译错误:外部程序无效

请帮忙!谢谢!

2 个答案:

答案 0 :(得分:0)

您的代码有点脱节,并尝试使用尚未变暗或实例化的变量。

Sub AstInv()
    Dim myTable As ListObject
    Dim myArray As range

    Set myTable = ActiveSheet.ListObjects("Table2")
    Set myArray = myTable.ListColumns("Código de Barras2").Range

    For Each cell In myArray
        If cell.Interior.Color = vbRed Then
            cell.EntireRow.Hidden = True
        End If
    Next
End Sub

答案 1 :(得分:0)

There are several issues with your code:

  • Compile error: Invalid outside procedure

    means that you have some random text at the top of your module (outside all Subs), as in:


random  ' <- Invalid outside procedure

Sub AstInv1()
    Dim myTable As ListObject
    Dim myArray As Variant
...

But there are more issues:

  • It is unlikely that you have a table named "Sheet2"
  • Your ActiveSheet (the sheet currently visible) may not contain the intended table / ListObject
  • myArray is declared as Variant when it should be Range
  • Rng and rw objects are undeclared and, as mentioned, are not connected to any other objects

To fix them

  • Use Option Explicit - this will force you to declare all variables
  • Check your objects' names and location
  • In the code call your objects explicitly

Option Explicit

Public Sub AstInv()
    Dim myTable As ListObject
    Dim myCol As Range
    Dim cell As Range

    Set myTable = ThisWorkbook.Worksheets("Sheet2").ListObjects("Table1")   'Check names
    Set myCol = myTable.ListColumns("Código de Barras2").Range

    For Each cell In myCol
        cell.EntireRow.Hidden = (cell.Interior.Color = vbRed)
    Next
End Sub

This version uses an AutoFilter and shows how to avoid errors when objects are missing


Option Explicit

Public Sub AutoFilterRedCells()
    Dim tbl As ListObject, col As Long

    On Error Resume Next    'Ignore expected errors

        Set tbl = ThisWorkbook.Worksheets("Sheet2").ListObjects("Table1") 'Check names
        col = tbl.ListColumns("Código de Barras2").Range.Column

    On Error GoTo 0         'Stop ignoring errors

    If col > 0 Then tbl.Range.AutoFilter Field:=col, Operator:=xlFilterNoFill

End Sub