将自定义函数复制到其他单元格(更改活动单元格)

我试图使这个自定义函数工作时,我复制了一些单元格。 这个函数应该用两个数字来填充两个数字之间的单元格。

Function HINT(FirstCell, LastCell) x = FirstCell.Column y = LastCell.Column a = FirstCell b = LastCell step = (b - a) / Abs(x - y) Actcellc = ActiveCell.Column HINT = FirstCell + (Actcellc - x) * step End Function 

它工作,如果我复制到第一个单元格和最后一个单元格之间的每个单元格,但不起作用,如果我只是select范围inbetween和复制(只计算每个单元格中的相同数字,因为它仍然看到活动单元格的起源如果我一个一个地复制活动单元格更改和function正常工作)。 我可以理解,我需要改变activecell定义为另一件事,但我只是不知道是什么。

提前致谢。

编辑:

我会在别人的帮助下回答我自己的问题:

 Function HINT(FirstCell, LastCell, pos As Range) Dim i As Long Dim res() As Double Dim rng As Range x = FirstCell.Column y = LastCell.Column a = FirstCell b = LastCell step = (b - a) / Abs(x - y) HINT = FirstCell + (pos.Column - x) * step End Function 

在第一个空白单元格中(在这种情况下,C2)代码应该像这样input:=提示($ B $ 2,$ N $ 2,C2)

$ B $ 2第一个值,固定/ $ N $ 2最后一个值,固定/ C2位置,第一个空白单元格被填充。

谢谢大家。

尝试一个数组函数:

 Function HINT2(FirstCell, LastCell) Dim i As Long Dim res() As Double x = FirstCell.Column y = LastCell.Column a = FirstCell b = LastCell step = (b - a) / Abs(x - y) ReDim res(1 To (y - x - 1)) As Double For i = 1 To y - x - 1 res(i) = FirstCell + i * step Next HINT2 = res End Function 

要使用它,请select两个边界之间的所有单元格,在公式栏中input函数名称和参数,然后按Ctrl + Shift + Enter

或者,您可以select提供一个“位置”参数,该参数将返回一个值,并允许轻松复制到多个单元格:

 Function HINT3(FirstCell, LastCell, pos As Long) Dim i As Long Dim res() As Double x = FirstCell.Column y = LastCell.Column a = FirstCell b = LastCell step = (b - a) / Abs(x - y) HINT3 = FirstCell + pos * step End Function 

你可能想在这个公式的上面连续的'position'数字1..n – 类似于这个:

在这里输入图像说明

另外,强烈build议声明variables。

您正在尝试填写多个单元格。 您需要一个返回数组或Sub的函数

这是子方法。 假设我们要填写A1M1之间的单元格

之前

这个小macros:

 Sub FillMissingInRow() Dim r As Range, v1 As Double, v2 As Double, inc As Double Set r = Range("A1:M1") v1 = r(1) v2 = r(r.Count) inc = (v2 - v1) / (r.Count - 1) r.DataSeries Rowcol:=xlRows, Type:=xlLinear, Step:=inc, Trend:=False End Sub 

将导致:

后