Excel VBAfunction在某些地方工作,但不是其他人

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

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 

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

奇怪的是,这个函数在一些CELLS中有效,但是在其他情况下它会抛出#N / A错误。 在有名字的单元格中。

任何人都可以帮我理解吗? 我不是VBA专家; 我在这个问题上做了一些研究,但是只find了比这更复杂的问题。

谢谢。

要知道他们的名字,你可以使用像这样的东西:

 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 

第二部分还将显示包含单元格的范围(如果没有find单引用的话)(输出以"* "开始(如果没有需要,可以删除)

尝试改变你的function:

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

某些表名称需要用引号括起来,以便保留语法规则。

编辑:基于来自David Zemens的评论,我更新了公式来执行Replace(cel.Parent.Name, "'", "''")以确保表格名称中的任何embedded式引号被replace为两个引号。