简体   繁体   中英

Excel VBA: Index-Match Multiple Criteria

I am trying to produce a VBA function that will hide all columns for which cells D9:CC9 are not equal to "A6" and cells D8:CC8 are not equal to "12." Based on the script below, the system keeps returning an error. I am new to VBA, was hoping someone might be able to assist.

Thanks!

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

Most operations are performed quite different using VBA than doing them manually. If you want to work with VBA then should do some research about working with variables and objects. This pages should be of interest.

Variables & Constants , Excel Objects , With Statement & Range Properties (Excel)

I have done some changes to your code, see comments within, and refer to the pages mentioned above.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM