excel - 如何在 VBA 中使用单元格值作为命名范围?

标签 excel vba

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

示例

Sheet2(命名为“文档 map ”)

 |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 中使用单元格值作为命名范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35705958/

相关文章:

vba - 查找行值,复制行及其下面的所有范围以减少数据

excel - 从 Word 文档访问 Excel 电子表格

VBA在循环中格式化数字以进行条件格式化

arrays - VBA 公共(public)数组 : how to?

ms-access - 如何在VBA中查找返回类型

excel - 有没有办法转换这个公式,使其区分大小写并且也适用于数字

当curl返回200时,VBA GET请求返回404

java - 在 java 中使用 MS Excel 查找表或任何类似的解决方案

mysql - 通过 ADO 创建/编辑记录时索引 MySQL 字段不保存值

excel - 选择excel表格中的列范围