【问题标题】:How can I use a Cell Value as a Named Range in VBA?如何在 VBA 中使用单元格值作为命名范围?
【发布时间】:2016-06-12 20:53:14
【问题描述】:

所以我的示例文档有两个工作表。在Sheet2 中,A 列填充有指向Sheet1 中命名单元格的超链接。作为参考,我需要将每个链接引用的命名范围的名称复制到另一个工作表中,在该工作表中,我还将记录位置相对于命名单元格位置的单元格中的其他项目。问题似乎是当我尝试从其中包含命名单元格名称的单元格值设置范围时。

示例

Sheet2(命名为“文档图”)

 |A                                             |B|
1|Link (address is #_123 which is a named cell) | |
2|Link 2 (address is #_89 which is a named cell)| |
3|Normal text cell, link location not recorded  | |

表 1

 |A                       |B                      |C|
1|(named _123)            |relevant info from _123| |
2|relevant info from _123 |                       | |
3|                        |relevant info from _123| |
4|relevant info from _123 |                       | |
5|(named _89)             |                       | |
6|                        |relevant info from _89 | |
7|relevant info from _89  |                       | |

我的 VBA

Option Explicit
Public Sub getOrderHeaderLocations()
    Dim rng As range
    Dim c As range
    Dim a As Hyperlink
    Dim r As Integer
    Dim tr As range
    Dim map As Worksheet
    Dim transList As Worksheet
    Dim table As Worksheet
    Set map = Sheets("Document map")
    Set transList = Sheets("Sheet1")
    Set table = Sheets.Add
    table.range("A1").Value = "Named Cell"
    table.range("B1").Value = "Info 1"
    table.range("C1").Value = "Info 2"
    table.range("D1").Value = "Info 3"
    map.Activate
    Set rng = range(map.range("A1"), "A" & map.range("A1").CurrentRegion.Rows.Count)
    'use a counter because not all lines have links and I don't want empty rows
    r = 2 'start in the second row of the table sheet (after headers)
    For Each c In rng.Cells
        If c.Hyperlinks.Count > 0 Then
            Set a = c.Hyperlinks.Item(1)
            table.range("A" & r).Value = a.SubAddress
            r = r + 1
        End If
    Next
    ' Glorious, I have a list of the cell names

    table.Activate
    ' set range to the list of names that we made
    Set rng = range(table.range("A2"), "A" & table.range("A2").CurrentRegion.Rows.Count)
    For Each c In rng.Cells
        r = c.Row
        ' set a range from the value of c which has the reference name of a cell)
        tr = range(c.Value) ' Error 91: Object variable or With block variable not set
        table.range("B" & r).Value = transList.range("B" & tr.Row).Value
    Next
End Sub

出现错误 91 时,我正在尝试设置单元格值的范围。我知道该单元格的名称确实存在,我可以通过在 excel 的名称框中输入值 (_123) 来验证这一点。我正在使用 Excel 2010。

【问题讨论】:

  • 设置范围时需要使用Set...Set tr = Range(c.Value)
  • 哇,总是小事!我不知道我是怎么错过的,谢谢!

标签: excel vba


【解决方案1】:

设置范围时需要使用Set

Set tr = Range(c.Value)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 2016-10-14
    • 2020-10-28
    • 1970-01-01
    • 2017-12-01
    • 2020-02-09
    • 1970-01-01
    相关资源
    最近更新 更多