根据列中的值创建命名范围

时间:2019-11-23 09:15:42

标签: excel vba named-ranges

我想基于B列中的值创建一个命名范围。

例如 (1,2,很棒) (5,21,缝制) (6、21,测试) (7,22,嗨) (1,21,随机)

我想创建一个名称范围为UNIT21的命名范围,从上面引用的数据中应该是A2:C4和A6:C6。另一个命名的range = UNIT22用于B列中有22的数据。

现在的问题是 1.我不知道如何从A:C中为整个行选择整个行。和, 2.如何将新数据添加到现有的命名范围,而不是像我的代码现在所做的那样替换现有值。

Excel VBA和编程的初学者。 谢谢!

cross-posted

Sub naming()
Dim row_index As Long
Dim lastrow As Long: lastrow = 5

Dim NamedRange As Range
Dim celltomap As Range

Dim Rng As Range

For row_index = 1 To lastrow


    RangeName = Sheet3.Range("A2:C6").Cells(row_index, 2).Value
    Set celltomap = Sheet3.Range("A2:C6").Cells(row_index, 3)

    Sheet3.Names.Add Name:="UNIT" & RangeName, RefersTo:=celltomap

    MsgBox ("UNIT" & RangeName)

    Next row_index


End Sub

enter image description here

2 个答案:

答案 0 :(得分:0)

这应该做:

Python 3.8.0 (default, Nov 21 2019, 17:20:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> str({1, 2})
'{1, 2}'

如您所见,我坚持使用原始的import sys; print(sys.version)设置模式,即:仅“ C”列单元格,但是您可以轻松地将代码闪烁起来并扩展到更多列

答案 1 :(得分:0)

运行以下代码,它将创建范围名称。

如果在运行代码之前未对列表进行排序,则命名范围的值将为{...}。

Sub NameRanges()

    Dim cUnique As Collection
    Dim Rng As Range
    Dim Cell As Range
    Dim sh As Worksheet
    Dim vNum As Variant
    Dim FrstRng As Range
    Dim UnionRng As Range
    Dim c As Range

    Set sh = ThisWorkbook.Sheets("Sheet1")
    With sh
        Set Rng = .Range("B2:B" & .Cells(.Rows.Count, "B").End(xlUp).Row)
        Set cUnique = New Collection

        On Error Resume Next
        For Each Cell In Rng.Cells
            cUnique.Add Cell.Value, CStr(Cell.Value)
        Next Cell
        On Error GoTo 0

        For Each vNum In cUnique
            For Each c In Rng.Cells
                If c = vNum Then
                    If Not UnionRng Is Nothing Then
                        Set UnionRng = Union(UnionRng, c.Offset(, 1))   'adds to the range
                    Else
                        Set UnionRng = c.Offset(, 1)
                    End If
                End If
            Next c

            UnionRng.Name = "Unit" & vNum
            Set UnionRng = Nothing
        Next vNum
    End With

End Sub

您有时可能想要删除范围名称并重新开始。

Sub delete_RngNames()
    Dim rn As Name
    For Each rn In ActiveWorkbook.Names
        rn.Delete
    Next rn
End Sub

您没有在工作表或UserForm上指示ActiveX组合框。

这对两个都应该起作用,只是buttonNames可能不同。

Private Sub CommandButton1_Click()
    Dim s As String, rng As Range, c As Range

    s = "Unit" & Me.TextBox1

    Me.ComboBox1.Clear

    For Each c In Range(s).Cells
        Me.ComboBox1.AddItem c
    Next c

End Sub

此代码假定您已在文本框中输入了内容。组合“单位”和文本框将指示要填充组合框的范围

相关问题