命名可变长度的许多范围

时间:2017-07-26 19:06:22

标签: excel vba excel-vba runtime-error named-ranges

我想在列中创建一个很长的值列表:

  • A1010标准基础
  • A101001 WALL FOUNDATIONS
  • A101001 COLUMN FOUNDATIONS& PILE CAPS
  • A1020特别基金会
  • A102001 PILE FOUNDATIONS

每个范围的名称应该是粗体细胞。

这是我到目前为止所做的事情,我确定它很笨重,但它是我的(有点);我已经从其他问题中找到的其他一些代码中拼凑出来。它应该用粗体文本减去空格来命名范围;然后重复删除命名范围,并使用每个新的非粗体字符串再次添加它。

当我尝试运行它时,我收到错误:运行时错误9;下标超出范围。

我想我已经挂在" RefersToR1C1"我搜索过的东西,但它对我没有意义。

Sub Change_Name()

Dim RngName As String
Dim MyADD As String

Sheets("Sheet 4").Select
Range("C2").Select

 While Not IsEmpty(ActiveCell.Value)

If ActiveCell.Font.Bold = True Then

ActiveCell.Replace " ", ""
RngName = ActiveCell.Value

Else

MyADD = ActiveWorkbook.Names(RngName).RefersToR1C1
MyADD = MyADD & "," & CStr(ActiveCell)
ActiveWorkbook.Names("RngName").Delete
ActiveWorkbook.Names.Add Name:="RngName", RefersToR1C1:=MyADD

End If

Selection.Offset(1, 0).Select

Wend

End Sub

我觉得我很接近,这是我几个小时前的想法。任何帮助表示赞赏。我只知道足够的vba来破坏事物并浪费我的时间,所以假设我什么都不知道。

1 个答案:

答案 0 :(得分:0)

我明白了。我不得不在名称中进行大量替换,因此它们可能是适当的范围名称。范围名称为粗体,值不是。

Option Explicit

Sub Change_Name()

Dim Rng As Range
Dim cell As String
Dim RngName As String
Dim MyADD As Range
Set MyADD = Nothing
Sheets("Sheet6").Select
Range("F1").Activate

Set Rng = Nothing

 While Not IsEmpty(ActiveCell.Value)

If ActiveCell.Font.Bold = True Then

ActiveCell.Replace " ", ""
ActiveCell.Replace "&", "_"
ActiveCell.Replace "/", "."
ActiveCell.Replace "-", ""
ActiveCell.Replace "(", "_"
ActiveCell.Replace ")", "_"
ActiveCell.Replace ",", "_"
RngName = ActiveCell.Value
Selection.Offset(1, 0).Select

    While ActiveCell.Font.Bold = False And IsEmpty(ActiveCell.Value) = False

        If Rng Is Nothing Then
            Set Rng = Range(ActiveCell.Address)
            Selection.Offset(1, 0).Select
        Else
            Set MyADD = Range(ActiveCell.Address)
            Set Rng = Union(Rng, MyADD)
            Selection.Offset(1, 0).Select
        End If
    Wend

    ActiveWorkbook.Names.Add Name:=RngName, RefersTo:=Rng
    Set Rng = Nothing

End If
  Wend

End Sub