1

How would I change this If statement to use an array Instead?

Dim with As Workbook: Set wb = ThisWorkbook

Dim sh As Worksheet: Set sh = wb.Worksheets("Sheet1")

Dim tbl As ListObject: Set table = ListObjects("Table1")

Dim lcount As Long: lounge = tbl.Range.Rows.Count

For x = 1 To lCount - 1

Sh.Cells(x + 1, 1).Value Like "*" & "Black" & "*" Then sh.Cells(x + 1, 2).Value = "Y"

Sh.Cells(x + 1, 1).Value Like "*" & "Yellow" & "*" Then sh.Cells(x + 1, 2).Value = "Y"

End sub
2
  • I think you'll need to edit this question. I don't see an array or If statement? What is the array? Commented Jul 6, 2022 at 5:00
  • Sorry I typed the question weird. I'm not familiar with how to manipulate arrays. This is how I currently get the task done and would like to know how to do the same thing using an array. Commented Jul 6, 2022 at 7:16

1 Answer 1

2

You can use this code:


'this ist the sub to show how to call the basic sub below

Public Sub test_selectColor()

    Dim tblData As ListObject

    Set tblData = ThisWorkbook.Worksheets(1).ListObjects("tblData")  '---> adjust this to your needs

    Dim arrCheckColors(1) As String
    'adding * to use the like operator against it
    arrCheckColors(0) = "*Black*"
    arrCheckColors(1) = "*Yellow*"

    selectColor tblData.DataBodyRange, arrCheckColors

End Sub


'this is the sub that does the work

Private Sub selectColor(rgData As Range, arrCheck() As String)

Dim arrData As Variant: arrData = rgData.Value   'read data to array

Dim iD As Long, iC As Long

For iD = LBound(arrData, 1) To UBound(arrData, 1)
    For iC = LBound(arrCheck) To UBound(arrCheck)
        If arrData(iD, 1) Like arrCheck(iC) Then
            arrData(iD, 2) = "Y"
            Exit For
        End If
    Next
Next

rgData.Value = arrData   'write array back to range

End Sub

But you could achieve the same by formula:

=LET(findColor,IFERROR(FIND(tblCheck[CheckColor],[@Color]),0), IF(SUM(findColor),"Y",""))

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.