根据两列中的条件创建范围

时间:2019-06-12 10:26:17

标签: excel vba

这与我最近发布的另一个问题有关,@ Stavros Jon很好地帮助了我。

我正在尝试根据B列和C列中的条件创建一个命名范围。如果B列包含单词“ OSI”并且C列包含单词“ Language”,我想创建一个范围。

我已经尝试编辑我以前的代码,但是我无法正确使用语法,并且计数器行出现对象错误。

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

如何编辑代码以包含这两个条件?

此外,有时我在B列中的文本将包含其他单元格中的单词,例如“过滤器”和“过滤器和搜索”,我也希望从C列单元格中的精确文本中确定我的范围,而不仅仅是“包含”本文。

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试一下

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