Create a range based on criteria in two columns

2019-08-02 06:08发布

This relates to another question I recently posted, which @Stavros Jon kindly helped me with.

I am trying to create a named range based on criteria in column B and column C. I want to create a range if column B contains the word "OSI" and column C contains the word "Language".

I have tried editing my previous code, but I cannot get the syntax right and get an object error with the counter line.

Sub another()

'Create Ranges:

Dim featuresRng As Range
Dim rng As Range
Dim sht As Worksheet
Dim counter As Long
Dim cell As Range
Set sht = ThisWorkbook.Worksheets("Features")
Set featuresRng = sht.Range(sht.Range("C1"), sht.Range("C" & sht.Rows.Count).End(xlUp)) 'dynamically set the range of features
Set featuresRng2 = sht.Range(sht.Range("B1"), sht.Range("B" & sht.Rows.Count).End(xlUp))

counter = 0 'this counter will help us avoid Union(Nothing, some range), which would give an error

For Each cell In featuresRng 'loop through the range of features
    If featuresRng.cell.Value = "Language" And featuresRng2.cell.Value = "OSI" Then
        counter = counter + 1
        If counter = 1 Then
            Set rng = sht.Range(cell.Offset(0, 1), cell.Offset(0, 3))
        Else
            Set rng = Union(rng, sht.Range(cell.Offset(0, 1), cell.Offset(0, 3))) 'build the range
        End If
    End If
Next cell
Debug.Print rng.Address
ThisWorkbook.Names.Add "OSILAng", rng

End Sub

How can I edit my code to include these two criteria?

Also, sometimes my text in column B will contain words in other cells, like "Filter" and "Filter and Search", I am also looking to make my range from the EXACT text in column C cells, not just 'contains this text.

Thanks in advance!

标签: excel vba
1条回答
仙女界的扛把子
2楼-- · 2019-08-02 06:37

Try this

Sub another()

Dim featuresRng As Range, NewArr As Variant
Dim rng As Range
Dim sht As Worksheet
Dim sRng As String
Dim i As Long

Set sht = ThisWorkbook.Worksheets("Features")
Set featuresRng = sht.Range(sht.Range("B1"), sht.Range("C" & sht.Rows.Count).End(xlUp))
rngArray = featuresRng
ReDim NewArr(1 To 1)
y = 1
For i = 1 To UBound(rngArray)
    If rngArray(i, 2) = "Language" And rngArray(i, 1) = "OSI" Then
        ReDim Preserve NewArr(1 To y)
        NewArr(y) = featuresRng.Rows(i).Offset(0, 3).Address
        y = y + 1

    End If
Next i

sRng = Join(NewArr, Application.DecimalSeparator)
ThisWorkbook.Names.Add "OSILAng", sht.Range(sRng)

End Sub
查看更多
登录 后发表回答