调用单元格中的函数时会返回错误的值

先发post。

长话短说,在Excel中,当我从一个单元格调用下面的函数(它在它自己的模块中)时,它返回错误的值。 函数返回正确的值时,从一个子,以及当我一步一步通过代码(到最后),但是我从Excel中调用它时,它返回一个不同的值。 在底部的背景。

我试过的东西

  • 使之成为公共职能
  • 给它一个参数
  • 更改function和/或模块名称
  • 将其移出模块
  • 重新启动Excel
  • 一堆随机的东西

这真的只是这个特定的function,给我这个问题,更简单的function做他们被告知。 我必须假设它与Excel正在做的事情的顺序有关,或者是函数可以改变的Excel部分的限制。

Function ActiveDisciplineFilters() Application.Volatile 'makes the function update automatically Dim disccolumn As Range Dim uniquedisc() As String Dim uniquediscstring As String 'create a string of unique values from the Discipline column i = 0 If Range("LayerList[Discipline]").SpecialCells(xlCellTypeVisible).Address = Range("LayerList[Discipline]").Address Then ActiveDisciplineFilters = "None" Exit Function End If For Each cell In Range("LayerList[Discipline]").SpecialCells(xlCellTypeVisible) If InStr(1, uniquediscstring, cell.Value) = 0 Then If i <> 0 Then uniquediscstring = uniquediscstring & ", " & cell.Value Else uniquediscstring = cell.Value i = 1 End If End If Next ActiveDisciplineFilters = uniquediscstring End Function 

背景

在Excel中,我有一个表。 我将所有数据放在该表的一个特定列中,并在该范围内创build一个唯一值的string(用逗号分隔)。 该string必须放置在另一个单元格中,原因是我不需要进入。 如果filter应用于列,则唯一值将自动更新。

当我从一个sub调用它的时候,Excel会给我正确的答案,当我从一个单元格调用它的时候,错误的答案会是什么?

不幸的是,没有一个SpecialCells方法在UDF中工作。 如果你需要从工作表中作为一个公式运行它,那么你的代码应该看起来像这样:

 Function ActiveDisciplineFilters() Application.Volatile 'makes the function update automatically Dim disccolumn As Range Dim uniquedisc() As String Dim uniquediscstring As String Dim i As Long Dim cell As Range Dim bHidden As Boolean 'create a string of unique values from the Discipline column i = 0 For Each cell In Range("LayerList[Discipline]").Cells If cell.EntireRow.Hidden = False Then If InStr(1, uniquediscstring, cell.Value) = 0 Then If i <> 0 Then uniquediscstring = uniquediscstring & ", " & cell.Value Else uniquediscstring = cell.Value i = 1 End If End If Else bHidden = True End If Next If Not bHidden Then uniquediscstring = "None" ActiveDisciplineFilters = uniquediscstring End Function