Excel VBA:索引匹配多个标准

时间:2015-10-20 23:13:52

标签: excel-vba vba excel

我正在尝试生成一个VBA函数,它将隐藏单元格D9:CC9不等于“A6”且单元格D8:CC8不等于“12”的所有列。根据下面的脚本,系统会不断返回错误。我是VBA的新手,希望有人能够提供帮助。

谢谢!

Dim MyCell As Range
       Set MyCell = Range("D9:CC9,D8:CC8")
             For Each cell In MyCell
                   If cell.Value <> WorksheetFunction.Index(Range("D9:CC9"),WorksheetFunction.Match(Range("A6")&"12",Range("D9:CC9")&Range("D8:CC8"), 0))
                        cell.EntireColumn.Hidden = True

                   End If

             Next cell

1 个答案:

答案 0 :(得分:0)

使用VBA执行大多数操作与手动执行完全不同。如果你想使用VBA,那么应该做一些关于使用变量和对象的研究。这页应该是有意义的。

Variables & ConstantsExcel ObjectsWith Statement&amp; Range Properties (Excel)

我对您的代码进行了一些更改,请参阅其中的注释,并参阅上述页面。

Sub Rng_HideColumns()
Dim rTrg As Range, rCol As Range
Dim sCllVal As String
    Rem Set rTrg = ThisWorkbook.Sheets("Sht(0)").Range("D9:CC9,D8:CC8")
    Rem Refers to the worksheet you want to work with instead or using the active worksheet
    With ThisWorkbook.Sheets("Sht(0)")

        Rem Get value to match
        sCllVal = .Range("A6").Value2 & 12

        Rem Set Range to Search
        Set rTrg = .Range("D8:CC9")
        For Each rCol In rTrg.Columns
            With rCol
                If .Cells(2).Value2 & .Cells(1).Value2 = sCllVal Then
                    .EntireColumn.Hidden = 1
                Else
                    .EntireColumn.Hidden = 0
    End If: End With: Next: End With
End Sub
相关问题