根据不在范围内的另一列中的值创建一个命名范围

时间:2019-06-11 08:15:58

标签: excel vba

我有一个数据集,宽10列,并且行数不断增加。

在C列中,我有一组功能,例如“搜索”将有对应的几行; ““过滤器”将具有与之对应的几行,依此类推。但是,它们可以以任何顺序排列,因此我可以具有一些“搜索”功能,然后具有一些“过滤器”功能,然后具有更多的“搜索”功能...

我需要为D:F列中的选定单元格创建一个命名范围,其中C中的值是我需要的功能。例如,这将是名为“ T1”的命名范围,该范围从D3:F6开始,对于所有“搜索”功能(而不是“过滤”功能),可能从D71:F71开始。

我尝试在名称管理器中使用“偏移量”和“计数”。但是理想情况下,我需要在我现有的宏中使用VBA,因此不需要每次添加新行时都更改命名范围。

理想情况下,代码将遵循... 如果列C包含单词“过滤器”,则每次出现单词“过滤器”时,请在其右侧的三列中命名一个范围。

我在名称管理器中使用了“偏移和计数”:

=OFFSET(Features!$D$3, 0, 0, COUNTA(Features!$D$3:$D$9), COUNTA(Features!$D$3:$F$3))

Sub mySub()

    Dim Features As Worksheet
    Dim myNamedRange As Range

    Dim myRangeName As String
    Set Features = ThisWorkbook.Worksheets("Search")

    If Range.("C") is "Search"
    Set mRangeName= myWorksheet.Range("D:F")

    myRangeName = "Search"

    ThisWorkbook.Names.Add Name:=Search, RefersTo:=myNamedRange

End Sub

任何帮助将不胜感激。我希望我已经足够澄清了这个问题。

1 个答案:

答案 0 :(得分:2)

如果我理解正确,那么您可以尝试以下操作:

Sub test()
Dim featuresRng As Range
Dim rng As Range
Dim sht As Worksheet
Dim counter As Long
Dim cell As Range

Set sht = ThisWorkbook.Worksheets("Name of your worksheet")
Set featuresRng = sht.Range(sht.Range("C1"), sht.Range("C" & sht.Rows.Count).End(xlUp)) 'dynamically set the range of features
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 cell.Value = "search" 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
sht.Names.Add "Something", rng
End Sub

上面的代码循环遍历要素范围,每当找到值为“搜索”的像元时,就会在该范围内添加相应的D,E和F像元。最终,您有了一个总范围,可以随意命名。

例如,如果您具有以下设置:

enter image description here

那么你会得到的是这样:

enter image description here

因此,结果范围地址将为$D$1:$F$2,$D$8:$F$8,$D$10:$F$12,$D$15:$F$19

现在,如果要在每次找到关键字时创建单个命名范围,则可以相应地修改代码,如下所示:

Sub test2()
Dim featuresRng As Range
Dim rng As Range
Dim sht As Worksheet
Dim counter As Long
Dim cell As Range

Set sht = ThisWorkbook.Worksheets("Name of your worksheet")
Set featuresRng = sht.Range(sht.Range("C1"), sht.Range("C" & sht.Rows.Count).End(xlUp)) 'dynamically set the range of features
counter = 0
For Each cell In featuresRng
    If cell.Value = "search" Then
        counter = counter + 1
        Set rng = sht.Range(cell.Offset(0, 1), cell.Offset(0, 3))
        sht.Names.Add "Something" & counter, rng
    End If
Next cell

End Sub