如何使用Excel VBA函数获取一系列单元格来单独计算而不是全部显示相同的值?

我已经在VBA中编写了一个函数,它查看某个附近单元格的内容,然后根据它们的值返回一个string。 我想要这个函数在整列的单元格上运行。 然而,当我填满时,每个单元格显示相同的值,无论我编辑和按下的单元格input。 我已经尝试设置Application.Volatile以及重新计算工作表(都使用F9ActiveSheet.Calculate ),但没有任何工作。 我也尝试设置ActiveCell.Value是我想要返回的string,然后不返回任何从函数,但Excel表示这是一个循环引用。 有什么build议么?

这是我的代码(的相关部分):

 Function foginSpeechP() Application.Volatile True ActiveSheet.Calculate '..... If scenario = "SR-1A" Then first = "nofog" secnd = "fog" ElseIf scenario = "SR-1B" Then first = "fog" secnd = "nofog" Else: foginSpeechP = "NOT A REAL SCENARIO in foginSpeechP" End If If (IsNumeric(ActiveCell.Offset(0, 4)) And ActiveCell.Offset(0, 4) > 0) Then currTimeStamp = ActiveCell.Offset(0, 4) Else: foginSpeechP = "NO TIME STAMP IN FOGINSPEECHP()" End If If currTimeStamp < speechFogChange Then foginSpeechP = first 'ActiveCell.Value = first Else: foginSpeechP = secnd 'ActiveCell.Value = secnd End If End Function 

问题在于你正在引用活动单元格,这可能是在该函数评估的时候由光标select的单元格。

做到这一点的方法是接受你的单元格偏移作为你的函数的参数:

 Function foginSpeechP(A) If scenario = "SR-1A" Then first = "nofog" secnd = "fog" ElseIf scenario = "SR-1B" Then first = "fog" secnd = "nofog" Else: foginSpeechP = "NOT A REAL SCENARIO in foginSpeechP" End If If (IsNumeric(A) And A > 0) Then currTimeStamp = A Else: foginSpeechP = "NO TIME STAMP IN FOGINSPEECHP()" End If If currTimeStamp < speechFogChange Then foginSpeechP = first 'ActiveCell.Value = first Else: foginSpeechP = secnd 'ActiveCell.Value = secnd End If End Function 

然后,假设你从A1调用,从你的工作表调用你的函数,如下所示:

 =foginSpeechP(E1) 

基本上,函数用来计算它的返回值的单元格的任何值都应作为parameter passing给函数。 有关更多详情,请参阅以下内容

http://www.cpearson.com/excel/writingfunctionsinvba.aspx

您应该使用Application.Caller获取input公式的单元格,而不是Activecell

您可能不会从工作表函数调用ActiveSheet.Calculate ,并使用ActiveCell是没有意义的。

你可能想用Application.CallerreplaceActiveCell

更好的是,将相关范围作为parameter passing给函数。