知道单元格的指定名称而不是“A1”名称

时间:2015-05-22 19:36:08

标签: excel vba excel-vba

上下文 我的表格中有几个列表(1列宽,1-10行长)。当我右键单击这些列表中的单元格时,我可以做几个选项,一切都运行良好。我给每个列表顶部的单元格命名(例如,单元格A1的名称为cell_1,B10的名称为cell_2,等等)。

我想知道我正确点击的单元格是否是列表顶部的单元格;它被命名为“cell_(number)”?如果不是,它会检查那个上面的单元格。它的名称是否以“cell_”开头?如果没有,请检查顶部的那个,等等。直到我可以找出用户点击WHICH列表的元素。

TL; DR实际问题 我可以使用ActiveCell.Address,这给了我类似“A1”的东西,无论我是否为该单元格指定了名称。 ActiveCell.Name给出了“Sheet1!A1”,所以它并没有好多少。知道如何让它返回我指定的名称吗?

2 个答案:

答案 0 :(得分:0)

创建一个UDF来测试应用程序名称,效率较低但在函数本身中包含错误处理:

// when all HTML is loaded on the page
// once the DOM is ready (short version)
$(function() {
    // make sure these elements are exeactly selected as intended by using a developer toolbar (usually key F12)
    var win = $(window),
        testimonials = $('.testimonials'),
        home = $('.home'),
        sitebrand = home.find('.siteBrand'),
        navbar = home.find('.x-navbar'),
        navwrap = home.find('.x-nav-wrap.desktop'),
        anchor = navwrap.find('.x-nav > li > a');

    // start initialising other libraries ...
    testimonials.bxSlider();

    // ... or add events
    sitebrand.click(function(){
        navbar.toggleClass('x-navbarOpen').addClass('ani');
        navwrap.toggleClass('siteBrandOpen').addClass("ani");
        anchor.toggleClass('menuOpen').addClass('ani');
    });

    win.scroll(function() {    
        navbar.toggleClass('x-navbar-fixed-top', win.scrollTop() >= 750);
    });
});

请注意,您也可以在工作表单元格中使用此功能,如下所示:

<强> = GetCellName(A1)

答案 1 :(得分:0)

也许这会奏效。此函数返回分配给单元格的名称(或更大范围)。如果有多个名称,则将其作为数组公式的数组返回...或者用户可以提供索引以仅返回所需的名称位置

Public Function CellIsInRangeNames(sheetname As String, checkRange As Range, Optional itemNumber As Variant) As Variant
   Dim oNM As Name
   Dim oSht As Worksheet
   Dim isect As Range
   Dim namesCollection() As Variant
   Set oSht = Worksheets(sheetname)

   Dim i As Integer
   i = -1
   For Each oNM In oSht.Names
       Set isect = Application.Intersect(Range(oNM.Name), checkRange)
       If Not isect Is Nothing Then
           i = i + 1
           ReDim Preserve namesCollection(0 To i)
           namesCollection(i) = CStr(oNM.Name)
       End If
   Next oNM

   If i = -1 Then
       'didn't find any
       CellIsInRangeNames = xlErrName
   ElseIf Not IsMissing(itemNumber) Then
       'user wanted this instance only
       If (itemNumber - 1 > UBound(namesCollection)) Or (itemNumber - 1 < LBound(namesCollection)) Then
           CellIsInRangeNames = xlErrValue
       Else
           CellIsInRangeNames = namesCollection(itemNumber - 1)
       End If
   Else  'here's the list as an array
       CellIsInRangeNames = namesCollection
   End If   

End Function