Excel VBA函数仅在查看时才返回答案

我正在使用Excel 2007.我在Excel VBA模块中具有以下function:

Function test(Loc, Dis) Dim StaRan As String Dim EndRan As String Application.Volatile ' Build the Start Range and End Range strings StaRan = Loc.Offset(-Dis, 0).Address EndRan = Loc.Offset(Dis, 0).Address ' Feed the range strings to Excel's Average function to get the answer test = WorksheetFunction.Average(Range(StaRan & ":" & EndRan)) End Function 

当插入到Excel工作表中时, test函数使用距离Dis作为正负行数来偏移位置Loc以构build可用于计算平均值的范围。 工作表被设置为手动计算,以便它不会更新,直到按F9button。

在Sheet1中input以下内容:

在单元格A2:1

在单元格A3:1

在单元格A4:1

在B3单元格:=testing(A3,1)

如果您正在查看放置函数(Sheet1)的工作表时,此函数可以工作(返回1),当您按F9时。 查看任何其他工作表(例如Sheet2)时,按F9键重新计算。 然后返回到原始工作表(Sheet1)并查看已返回的test 。 它返回了#VALUE! 。 如果您在查看原始工作表(Sheet1)的同时再次按下F9,则会返回正确的答案。

这是一个Excel错误? 有没有解决的办法?

Range()指的是活动表,除非你有资格。

这更直接:

 Function test(Loc, Dis) Application.Volatile test = WorksheetFunction.Average(Loc.Offset(-Dis,0).Resize((2*Dis)+1)) End Function