vba - Excel VBA 函数在某些地方有效,但在其他地方无效

标签 vba excel

我将以下简单函数插入到电子表格的模块中:

Function CellName(cel As Range) As Variant
Dim nm As Name
    For Each nm In Names
        If nm.RefersTo = "=" & cel.Parent.Name & "!" & cel.Address Then
            CellName = nm.Name
            Exit Function
        End If
    Next
CellName = CVErr(xlErrNA)
End Function

我只想用相邻列中单元格的命名变量填充一列。

奇怪的是,这个函数在某些单元格中有效,但在其他单元格中它会抛出 #N/A 错误。在确实有名称的单元格中。

谁能帮我理解一下吗?我不是 VBA 专家;我确实对这个问题做了一些研究,但只找到了比这个更复杂的问题的答案。

谢谢。

最佳答案

要获取它们所在位置的名称,您可以使用如下内容:

Public Function CellName(cel As Range) As Variant
  Dim nm As Name, sht As Worksheet

  For Each nm In ThisWorkbook.Names
    If nm.RefersTo = "=" & cel.Parent.Name & "!" & cel.Address Then
      CellName = nm.Name
      Exit Function
    End If
  Next

  For Each sht In ThisWorkbook.Worksheets
    For Each nm In sht.Names
      If nm.RefersTo = "=" & cel.Parent.Name & "!" & cel.Address Then
        CellName = nm.Name
        Exit Function
      End If
    Next
  Next

  '----- skip from here if you only want single-cells

  For Each nm In ThisWorkbook.Names
    If Not Intersect(Range(nm.RefersTo), cel) Is Nothing Then
      CellName = "* " & nm.Name
      Exit Function
    End If
  Next

  For Each sht In ThisWorkbook.Worksheets
    For Each nm In sht.Names
      If Not Intersect(Range(nm.RefersTo), cel) Is Nothing Then
        CellName = "* " & nm.Name
        Exit Function
      End If
    Next
  Next

  '----- skip till here if you only want single-cells

CellName = CVErr(xlErrNA)

End Function

如果没有找到单一引用,第二部分还将显示包含单元格的范围(输出以“*”开头(如果不需要,可以删除)

关于vba - Excel VBA 函数在某些地方有效,但在其他地方无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40726836/

相关文章:

Vba Excel - 如果值=值过滤并复制到正确工作表上 - 加速

vba - MS Access VBA acImport 工作表名称,带空格和范围

java - 使用 spring Batch 和 apache poi 从多个源写入数据

java - 使用 apache poi 方法检查 excel 中的空行

java - Apache Poi Android

excel - 删除多行单元格中的第一行

vba - 如何创建文件名中包含特殊字符的文本文件

vba - 选择从 3 到 305 的所有奇数行

excel - 如何防止Excel单元格更新?

VBA 查找和替换